测试具有超时的axios api调用

问题描述 投票:3回答:1

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

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

unit-testing jestjs axios
1个回答
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");
});

这不像我想的那么干净,因为我不想修改测试的生产代码,但由于它很小,我没有找到更好的替代方案,它比没有测试更好。

© www.soinside.com 2019 - 2024. All rights reserved.