简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM