Baj*_*jju 8 unit-testing jestjs axios
我有一个axiosapi ,我为其设置默认超时 5000 毫秒(5 秒)。我想对一个存根进行单元测试,它应该向我抛出超时异常/承诺拒绝并带有错误代码ECONNABORTED。但是每当我尝试使用 moxios 模拟后调用 api 时,都会收到此错误:Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
PS:用作Jest我的测试运行。
我遇到了类似的问题,我想测试 Axios 周围的包装函数超时后重定向到错误页面。对于我的测试,我使用超级测试,它更多的是集成测试,但它应该工作相同。
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,
        }
}
Run Code Online (Sandbox Code Playgroud)
然后在测试之前设置环境变量并在之后将其删除,这样它就不会导致其他测试出现问题:
beforeEach(() => {
    server = require("../server");
    process.env.testTimeout = 1    //set the environment variable
});
afterEach(() => {
    server.close();
    process.env.testTimeout = undefined   //remove environment variable 
});
Run Code Online (Sandbox Code Playgroud)
考试:
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");
});
Run Code Online (Sandbox Code Playgroud)
这并不像我想要的那么干净,因为我不想修改测试的生产代码,但由于它很小而且我还没有找到更好的替代方案,所以它比没有测试要好。
|   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           5096 次  |  
        
|   最近记录:  |