Jest needs to create the __test__ folder, where the single-test code is executed by default

Component single test is relatively simple. We use the method provided by MiniProgram-SIMULATE directly:

const simulate = require('miniprogram-simulate') const path = require('path') function testHandler(desc, Fn) {test(desc, () => {try {fn() console.log(' ${desc} ')} catch (e) {console.log(' ${desc} ') ${e} ')}})} function expectHandler(actual) {const ID = BE.load (path.join(__dirname, '.. /.. /src/component/add-tip/index')) const comp = simulate.render(id) const parent = document.createElement('parent-wrapper')  comp.attach(parent) // const view = comp.querySelector('.add-tip') const that = comp.instance logic(that.data.isShow).toBe(! Store = {setItem: jest.fn()}; // console.log(thate.store.setitem.mock) thate.close () // call the close method of the component Logic (tha.data.isshow).tobe (actual)} function logic(result) {return {toBe: function (actual) { if (result ! == actual) {throw Error(${actual}, Result is ${result} ')}}}} testHandler(' Add-tip component isShow variable ', () => expectHandler(false))Copy the code

Because miniProgram-SIMULATE’s Page and life hooks are not available, we need to configure Page globally ourselves:

export const noop = () => {}; export const isFn = fn => typeof fn === 'function'; let wId = 0; global.Page = ({ data, ... rest }) => { const page = { data, setData: jest.fn(function (newData, cb) { this.data = { ... this.data, ... newData, }; cb && cb(); }), onLoad: noop, onReady: noop, onUnLoad: noop, __wxWebviewId__: wId++, ... rest, }; global.wxPageInstance = page; return page; }; global.getApp = function () { return { baseUrl: 'https://m.maizuo.com/v4/api', }; }; global.Date.now = jest.fn(() => 1536708613825); global.wx = { showLoading: jest.fn(), hideLoading: jest.fn(), showModal: jest.fn(), request: jest.fn(), getStorageSync: jest.fn(), showShareMenu: jest.fn(), }; module.exports = global;Copy the code

Then the development of page-level single test was carried out:

import global from '.. /.. /wx.js' import '.. /.. /src/subPages/redPacket/redPacketDetail' import api from '.. /.. /src/http/api' import { post } from '.. /.. / SRC/HTTP /request' const page = global.wxpageInstance describe(' describe ', () => {describe('onLoad', () => { beforeAll(() => { page.api = api page.post = post jest.spyOn(page, 'initPage') jest.spyOn(page, 'getDayName') page.onLoad(); }); it('should getDayName', (done) => {// expect. Assertions (1) expect(page.getdayName ('2021-06-23 10:37:20')).toequal (' today ') done()}) // it('should  initPage', (done) =>{ // const params = { // page_index: 1, // page_size: 20 // } // page.initPage(params) // console.log(page.data) // Expect (page. Data. NewList [0]. Readable_business). ToEqual (' withdrawal); // done() // }) }) })Copy the code

Single test of complex project pages, or a bit of trouble, many business interfaces to do anti-injection, not good single test.