我的组件如下:
<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)
},
}
最后,AxiosService
是axios
发布的地方。
我想为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.
}
})
})
})
在运行此测试时,我希望根据我的模拟json将numberOfRecords
更新为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的新手。我很难理解这里出了什么问题以及如何解决。
答案 0 :(得分:0)
预计trigger('click')
之后不会立即更新数据。此外,由于将其设置为“ 10”字符串,因此不应为10。如果测试失败有正确的错误输出,$nextTick
将对此提供有用的反馈。
expect
之所以出现,是因为存在未处理的承诺拒绝,它不会导致测试失败。 UnhandledPromiseRejectionWarning
承诺未链接到从测试功能返回拒绝的承诺。最简单的方法是then(...)
语法:
async..await
如果it('We get a success', async () => {
...
wrapper.find('button').trigger('click')
await wrapper.vm.$nextTick()
expect(wrapper.vm.$data.numberOfRecords).toBe('10')
})
应该是数字并用于数学运算,则应在JSON响应中或在处理它的位置将其强制为数字:
numberOfRecords