测试具有超时的axios api调用

时间:2017-11-16 03:22:11

标签: unit-testing jestjs axios

我有一个axios api,为此我将默认超时设置为5000毫秒(5秒)。 我想对一个存根进行单元测试,该存根应该使用错误代码ECONNABORTED抛出超时异常/承诺拒绝。 但每当我尝试使用moxios模拟它后调用api,我都会收到此错误:Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

PS:使用Jest作为我的测试运行。

1 个答案:

答案 0 :(得分:0)

我有一个类似的问题,我想在围绕Axios的包装函数中超时后测试重定向到错误页面。对于我的测试,我使用的是supertest,它更多的是和集成测试,但是它应该可以正常工作。

const doRequest = async (req, requestConfig) => {
    requestConfig.timeout = process.env.testTimeout || requestTimeout 
    // if the environment variable testTimeout is set use that otherwise use the one from config

    const axiosResponse = await axios(requestConfig)

        return {
            data: axiosResponse.data,
            headers: axiosResponse.headers,
        }
}

然后在测试之前设置环境变量,并在之后将其删除,以免对其他测试造成问题:

beforeEach(() => {
    server = require("../server");
    process.env.testTimeout = 1    //set the environment variable
});

afterEach(() => {
    server.close();
    process.env.testTimeout = undefined   //remove environment variable 
});

测试:

it("should return 302 and redirect to error page if service call exceeds timeout", async () => {
        const res = await callSomeEndpoint();

        expect(res.status).toBe(302);
        expect(res.redirect).toBe(true);
        expect(res.header.location).toBe("https://example.com/error");
});

这不像我想要的那样干净,因为我不想修改测试的生产代码,但是由于它很小,而且我没有找到更好的替代方法,所以总比没有测试要好。

>