【问题标题】:testing axios api call which has a timeout测试有超时的 axios api 调用
【发布时间】:2018-04-29 11:34:41
【问题描述】:

我有一个 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】:

    我有一个类似的问题,我想在 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");
    });
    

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

    【讨论】:

      猜你喜欢
      • 2018-02-21
      • 1970-01-01
      • 1970-01-01
      • 2020-04-01
      • 2020-08-16
      • 2016-07-19
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      相关资源
      最近更新 更多