typescript - Jest taking longer than expected to run tests using axios mock-adapter - Stack Overflow

I am using jest to test that my API functions return the correct latency spent by axios when doing the

I am using jest to test that my API functions return the correct latency spent by axios when doing the API calls. In the tests, I use the 'axios-mock-adapter' library to simulate delays in axios calls such that my functions can return these latency values then I can assert them in my unit tests. When running these latency unit tests just by themselves (jest -- latencies.test.ts) in their own file, the mocked delays assert successfully. But when running all the unit tests in the whole repo, the assertions on latency fail with the actual axios delays higher than the values I set in the mock adapter.

Here is my code:

import MockAdapter from 'axios-mock-adapter';
import axios, { AxiosInstance } from 'axios';

const CLIENT_TIMEOUT_MILLI = 8000;

export const getCar = async (carId: string) => {
    const axiosInstance = axios.create({
        timeout: CLIENT_TIMEOUT_MILLI,
    });

    const startTime = new Date().getTime();
    const response = await axiosInstance.get(`/cars/${carId}`);
    const endTime = new Date().getTime();

    return {
        data: response.data,
        status: response.status,
        latency: endTime - startTime,
    };
};

const API_DELAY = 100;

describe('Cars APIs', () => {
    let axiosInstance: AxiosInstance;
    let mockAdapterInstance;

    beforeEach(() => {
        axiosInstance = axios.create({
            timeout: 3000,
        });

        mockAdapterInstance = new MockAdapter(axiosInstance, { delayResponse: API_DELAY });
    });

    afterEach(() => {
        mockAdapterInstance.reset();
    });

    it('Gets list of cars successfully', async () => {
        const responseMock = { status: 504, latency: API_DELAY };

        mockAdapterInstance.onGet('/cars').reply(responseMock.status, {});

        const result = await getCars();

        expect(result.status).toStrictEqual(responseMock.status);
        expect(result.latency).toBeCloseTo(responseMock.latency, -1);
    });

    it('Gets car successfully', async () => {
        const responseMock = { status: 504, latency: API_DELAY };

        mockAdapterInstance.onGet('/cars/012').reply(responseMock.status, {});

        const result = await getCar();

        expect(result.status).toStrictEqual(responseMock.status);
        expect(result.latency).toBeCloseTo(responseMock.latency, -1);
    });
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745306357a4621732.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信