乐趣区

关于javascript:vuejest-项目中的单测持续更新

刚开始接触 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)
  })
退出移动版