繁体   English   中英

如何在单元测试之前等待异步调用在组件的挂载回调中完成?

[英]How to wait for an async call to finish in component's mount callback before unit testing it?

我正在使用 Jest 对在其mounted()方法中调用 Axios 的组件进行单元测试。 我是 mocking Axios 调用所以它返回 promise 所以 API 调用实际上没有进行。 但问题似乎是因为 Axios 是异步的,我如何告诉我的测试在运行我的期望之前等待 Axios 调用(甚至是假的)完成?

这不起作用:

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');
});

如果我在超时时间包装它,它确实有效。 我想我读过这是因为超时总是在 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);
});

有一个更好的方法吗?

谢谢!

未经测试,但以下不起作用吗?

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');
});

(你需要添加https://www.npmjs.com/package/flush-promises (或者自己写,大概4行代码,返回一个resolved promise)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM