刚开始接触jest, 原理api啥的网上一堆,仅本人写我的项目记录下,有问题能够留言一起学习

emit事件

页面:

  handleClose() {        this.$emit('update:isShow', false) },

jest:

  test('handleClose', () => {    wrapper.vm.handleClose()    expect(wrapper.emitted().update).toBeFalsy()  })

事件总线 eventBus

页面:

read(){           this.$message.success('操作胜利')            this.$EventsBus.$emit('headerMsgTips')            this.$EventsBus.$emit('unReadySendMsg')            this.msgPageNamber = 1            this.msgList = []            this.getAllMessageList()}

jest:

const $message = {  error: jest.fn(),  warning: jest.fn(),  success: jest.fn()}const wrapper = mount(allMsgList, {  localVue,  data() {    return {}  },  router,  mocks: {    $message,    $EventsBus: {      $emit: jest.fn()    }  }})//======  test('read', async () => {    jest.mock('@/api/workBeanch/index.js')    msgApi.checkMessageAllRead.mockResolvedValue({ code: 1 })    jest.spyOn(wrapper.vm, 'getAllMessageList')    await wrapper.vm.read()    Vue.nextTick()    expect(wrapper.vm.$message.success.mock.calls[0][0]).toBe('操作胜利')    expect(wrapper.vm.msgPageNamber).toBe(1)    expect(wrapper.vm.msgList).toEqual([])   expect(wrapper.vm.$EventsBus.$emit).toHaveBeenCalledTimes(2)   expect(wrapper.vm.getAllMessageList).toBeCalledTimes(1)  })

路由跳转router + window api

页面:

     goBmsDetail(id) {        let routeData = this.$router.resolve({          path: '/caseDetail/bmsDetail' + `?id=${id}`        })        window.open(routeData.href, `/caseDetail/bmsDetail?id=${id}`)      },

jest:

  test('goBmsDetail', () => {    delete window.location //这里要重写一下 不便前面mock掉    window.location = { reload: jest.fn() }    window.location.reload = jest.fn()    window.open = jest.fn()    const spy = jest.spyOn(wrapper.vm.$router, 'resolve')    wrapper.vm.goBmsDetail(123)    expect(spy.mock.calls[0][0].path).toEqual('/caseDetail/bmsDetail?id=123')    expect(window.open).toBeCalledTimes(1)  })