vue+jest 專案中的單測,持續更新..

那年發表於2022-04-22

剛開始接觸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)
  })

相關文章