[英]How to wait for an async call to finish in component's mount callback before unit testing it?
I'm using Jest to unit test a component that makes an Axios call in it's mounted()
method.我正在使用 Jest 对在其
mounted()
方法中调用 Axios 的组件进行单元测试。 I'm mocking the Axios call so it returns a promise so the API call is not actually made.我是 mocking Axios 调用所以它返回 promise 所以 API 调用实际上没有进行。 But the problem seems to be that because Axios is asynchronous, how do I tell my test to wait for the Axios call (even the fake one) to complete before running my expectations?
但问题似乎是因为 Axios 是异步的,我如何告诉我的测试在运行我的期望之前等待 Axios 调用(甚至是假的)完成?
This does not work:这不起作用:
it('calls auth api', () => {
spyOn(axios, 'get').and.callFake(() => Promise.resolve().then(() => authResponse));
wrapper = shallowMount(App, {
localVue,
});
expect(axios.get).toHaveBeenCalledWith('api/auth');
// The "status" data is set in the axios callback. But this fails.
expect(wrapper.vm.status).toBe('AUTHORIZED');
});
If I wrap it in a timeout, it does work.如果我在超时时间包装它,它确实有效。 I think I've read this is because the timeouts are always called after promises are resolved or something?
我想我读过这是因为超时总是在 promise 解决之后调用?
it('calls auth api', () => {
spyOn(axios, 'get').and.callFake(() => Promise.resolve().then(() => authResponse));
wrapper = shallowMount(App, {
localVue,
});
expect(axios.get).toHaveBeenCalledWith('api/auth');
setTimeout(() => {
expect(wrapper.vm.status).toBe('AUTHORIZED');
}, 0);
});
Is there a better way to do this?有一个更好的方法吗?
Thanks!谢谢!
Untested, but does the following not work?未经测试,但以下不起作用吗?
const flushPromises = require('flush-promises');
it('calls auth api', async () => {
spyOn(axios, 'get').and.callFake(() => Promise.resolve().then(() => authResponse));
wrapper = shallowMount(App, {
localVue,
});
await flushPromises(); // <<
expect(axios.get).toHaveBeenCalledWith('api/auth');
});
(You will need to add https://www.npmjs.com/package/flush-promises (or write your own, it is about 4 lines of code, returning a resolved promise) (你需要添加https://www.npmjs.com/package/flush-promises (或者自己写,大概4行代码,返回一个resolved promise)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.