testing axios api call which has a timeout

Viewed 3277

I have an axios api , for which I am setting the default timeout of 5000ms (5 secs). I would like to unit test a stub which should throw me the timeout exception/ promise rejection with the error code ECONNABORTED. But whenever I try to call the api after mocking it using moxios, I get this error : Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.

PS: using Jest as my test running.

1 Answers

I had a similar issue where I wanted to test redirecting to an error page after a timeout in a wrapper function around Axios. For my test im using supertest and it's more of and integration test but it should work the same.

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,
        }
}

Then before the test set the environment variable & remove it after so it doesn't cause problems with your other tests:

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

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

The test:

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

This isn't as clean as I'd like since I don't want to be modifying production code for a test, but since it's minimal and I haven't found a better alternative it's better than no test.

Related