头图

vue+jest 项目中的单测,持续更新..

那年
English

刚开始接触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)
  })
阅读 381

生产力
开发环境的配置 提高生产力的工具
103 声望
11 粉丝
0 条评论
103 声望
11 粉丝
文章目录
宣传栏