【问题标题】:Vue Jest Unit TestVue Jest 单元测试
【发布时间】:2020-08-04 05:03:00
【问题描述】:

我有一个组件如下:

<template>
   <h1>{{ numberOfRecords }}</h1>
   <button @click="callMe">Update</Button>
</template>

<script>
import MyService from '../services/MyService'
export default {
  name: 'MyComponent',

  data() {
    return {
      numberOfRecords: 0,
    }
  },

  methods: {
    async callMe() {
        try {
          console.log('calling post')
          const myResponse = await MyService.postSomething(this.data)
          this.numberOfRecords = bulkUpdateResponse.data.numberOfRecords
        } catch (error) {
          const message = error.response ? error.response.data : error
          console.log(message)
        }
      }
    },
  },
}
</script>

<style>

</style>

MyService.js 就像:

import AxiosService from './AxiosService'

const resourceUrl = 'rest/myrestpath'

export default {
  postSomething(data) {
    return AxiosService.post(`${resourceUrl}/somepath`, data)
  },
}

最后,AxiosServiceaxios 发帖的地方。

我想为 MyComponent 编写单元测试,其中我想模拟 MyService.postSomething 以返回模拟数据并避免 axios 调用。

我的MyComponent.spec.js 看起来像:

import { mount } from '@vue/test-utils'
import MyComponent from '../../src/views/MyComponent.vue'
import MyService from '../../src/services/MyService.js'

jest.mock('../../src/services/MyService')

describe('MyComponent.vue', () => {
    beforeEach(() => {
      // Clear all instances and calls to constructor and all methods
      MyService.postSomething.mockClear()
    })

it('We get a success', () => {
    const resp = { data: { numberOfRecords: '10' } }
    MyService.postSomething.mockImplementation(() => resp)

    const wrapper = mount(MyComponent)

    wrapper.find('button').trigger('click')
    expect(wrapper.vm.$data.numberOfRecords).toBe(10)  // why not updated ?

    wrapper.vm.$nextTick().then(() => {
      expect(wrapper.vm.$data.numberOfRecords).toBe(10)  // still not updating. getting error.
    }
   })
  })
})

在运行此测试时,我希望 numberOfRecords 根据我的模拟 json 更新为 10。但是,这不会发生在我的第一个 expect 语句所在的位置。

然后我想我必须把它放在$nextTick() 中,但是它仍然不起作用。我得到了错误:

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:15964) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我是 Vue 和 Jest 的新手。我很难理解这里出了什么问题以及如何解决它。

【问题讨论】:

    标签: unit-testing vue.js jestjs


    【解决方案1】:

    预计不会在trigger('click') 之后立即更新数据,这就是$nextTick 的用途。此外,它不应该是 10 个数字,因为它被设置为 '10' 字符串。如果失败的测试有正确的错误输出,expect 将提供有用的反馈。

    UnhandledPromiseRejectionWarning 出现是因为存在未处理的 Promise 拒绝,它不会导致测试失败。 then(...) promise 没有被链接以从测试函数返回被拒绝的 promise。最简单的不让它脱离链接的方法是async..await 语法:

    it('We get a success', async () => {
        ...
        wrapper.find('button').trigger('click')
        await wrapper.vm.$nextTick()
        expect(wrapper.vm.$data.numberOfRecords).toBe('10')
    })
    

    如果numberOfRecords 应该是一个数字并用于数学运算,则应该强制它是一个数字,无论是在 JSON 响应中还是在处理它的地方:

    this.numberOfRecords = +bulkUpdateResponse.data.numberOfRecords
    

    【讨论】:

      猜你喜欢
      • 2019-01-02
      • 2021-01-24
      • 2019-04-03
      • 2020-07-31
      • 2018-12-16
      • 2018-12-24
      • 2022-01-06
      • 2022-01-02
      • 1970-01-01
      相关资源
      最近更新 更多