Pau*_*ler 5 jasmine moxios axios-mock-adapter
我尝试在从服务器获取某些内容后测试其渲染。我使用Vue Test Utils
但这无关紧要。
在created
组件的钩子中,ajax 调用是通过axios
. 我注册axios-mock-adapter
响应并“渲染”组件,进行调用,一切正常,但我必须使用该moxios
库来等待请求完成。
it('displays metrics', (done) => {
this.mock.onGet('/pl/metrics').reply((config) => {
let value = 0
if (config.params.start == '2020-01-26') {
value = 80
}
if (config.params.start == '2020-01-28') {
value = 100
}
return [200, {
metrics: [
{
key: "i18n-key",
type: "count",
value: value
}
]
}]
})
.onAny().reply(404)
let wrapper = mount(Dashboard)
moxios.wait(function() {
let text = wrapper.text()
expect(text).toContain('80')
expect(text).toContain('100')
expect(text).toContain('+20')
done()
})
})
Run Code Online (Sandbox Code Playgroud)
是否有可能摆脱moxios
并仅使用它来实现相同的效果axios-mock-adapter
?
flushPromises
是的,您可以使用 async/await实现自己的方法:
const flushPromises = () => new Promise(resolve => setTimeout(resolve))
it('displays metrics', async () => {
this.mock.onGet('/pl/metrics').reply((config) => {
// ..
}).onAny().reply(404)
let wrapper = mount(Dashboard)
await flushPromises()
expect(text).toContain('80')
})
Run Code Online (Sandbox Code Playgroud)
或者使用done
和setTimeout
:
it('displays metrics', (done) => {
this.mock.onGet('/pl/metrics').reply((config) => {
// ..
}).onAny().reply(404)
let wrapper = mount(Dashboard)
setTimeout(() => {
expect(text).toContain('80')
done()
})
})
Run Code Online (Sandbox Code Playgroud)
moxiois.wait
只需使用 安排回调setTimeout
。这是有效的,因为由 setTimeout 调度的任务总是在微任务队列(如 Promise 回调)清空后运行。
归档时间: |
|
查看次数: |
3982 次 |
最近记录: |