Search code examples
reactjsunit-testingjestjsts-jestjest-fetch-mock

How We can mock test multiple api calls in jest testing


I have a scenario like i have to call 1stAPI then depending on the response of 1st API i have to call 2nd API.

I got a solution to test 1st API :

global.fetch = jest
  .fn()
  .mockImplementation(() => getMockPromise({ Response: resMock }));

I got my 1st response while mocking but how can I get response in second ? I am using typescript with react

I tried to search multiple places but only got solution for one mock response only for jest testing like below :

global.fetch = jest
  .fn()
  .mockImplementation(() => getMockPromise({ Response: resMock }));

I thought if I use the above mockImplementation two times for different response it will work, but still same only one is working.


Solution

  • If you are calling fetch() with different arguments each time, you can use a mock implementation that responds with different data depending on the argument it receives.

    //test file
    const mockedResponses = {
      'firstUrl': {}, // first response object
      'secondUrl': {}, // second response object
    }
    
    global.fetch = jest
      .fn()
      .mockImplementation((url: string) => getMockPromise({ Response: mockedResponses[url] }));
    
    

    Generally it's a good idea to have the actual fetch() call be done inside a separate function, e.g. callFirstApi() and callSecondApi(), and then you can just mock those functions instead. This also means you don't end up overwriting a global function.

    You can also look into something like the Nock package which lets you do more elaborate testing of external APIs.