Search code examples
javascriptunit-testingmockingjestjsspyon

How can I mock multiple different database calls in a unit test with jest?


I am writing a jest unit test for a function that makes multiple different database calls. I am able to mock the first db call just fine but I am having trouble mocking the others.

My function:

const sample = async () => {
   const resultsFromCallOne = await dbClient.makeCall('...');
   const resultsFromCallTwo = await dbClient.makeCall('...');
   const resultsFromCallThree = await dbClient.makeCall('...');
}

My test file:

const mock = jest.spyOn(dbClient, 'makeCall');
mock.mockImplementation(() => Promise.resolve({
  return [1, 2, 3];
}));

mock.mockImplementation(() => Promise.resolve({
  return [4, 5, 6];
}));

mock.mockImplementation(() => Promise.resolve({
  return [7, 8, 9];
}));

sample();

When I run that test, the results of all 3 db calls is equal to the last mock [7, 8, 9]. Could someone please guide me on how to properly mock the three calls?

Thank you in advance!


Solution

  • Does each call have different params? If so I'd recommend jest-when. https://www.npmjs.com/package/jest-when

    With that you could mock out specific returns for given sets of parameters.

    Edit to add another option. You could utilize mockResolvedValueOnce. https://jestjs.io/docs/en/mock-function-api#mockfnmockresolvedvalueoncevalue

    This would replace the need to return a promise, but would be more brittle because it would depend on the order the mock is called.