Home > Net >  How to use Typescript, Jest and Axios to mock two different requests in the same unit test?
How to use Typescript, Jest and Axios to mock two different requests in the same unit test?

Time:09-02

So I have function A and function B

function A does a GET request

function B does a GET request

function B is inside function A

I want to test the function A, and in order to do that I need to mock two GET requests(one mock for each function) to different endpoints with different responses. How can I do that using Jest and Axios?

I couldn't figure out how to mock the second call:

it("test", async () => {
    mock.get.mockResolvedValue({ data: RESPONSE });

    const response = await functionA(input);

    expect(response).toMatchObject({ status: 1 });
    expect(response.value).toMatchObject({
      state: { status: "OK" },
      data: RESPONSE,
    });
  });

CodePudding user response:

This solved my problem:

mock.get.mockImplementation((url) => {
      switch (url) {
        case 'URL_A':
          return Promise.resolve({data: data_A})
        case 'URL_B':
          return Promise.resolve({data: data_B})
        default:
          return Promise.reject(new Error('error message'))
      }
    })

CodePudding user response:

A good alternative could be to use the mockResolvedValueOnce(...) method.

  • Related