My application code is something like this:
const promises = requests.map(async request => {await someAPI(request)});
await Promises.all(promises);
I don't care about the return value.
I have a mock for the API like
const someAPI = jest.fn().mockReturnValue(Promise.resolve(true));
I can test that someAPI is called with the right parameters, but how can I test that the returned promise is indeed resolved? For example, if the client code is simply
const promises = requests.map(async request => {await someAPI(request)});
It would pass the test for calling the API, even though it doesn't actually try to resolve the promises.
I tried the suggestion, but this still doesn't work.
let promiseResolved = false;
someAPI.mockImplementation(
() =>
new Promise((resolve) => {
promiseResolved = true;
resolve();
})
);
When the method calls
const promises = requests.map(async request => {await someAPI(request)});
The boolean is already set to true. In reality, the API isn't even called if I don't do the Promise.all step.
If you declare a local boolean initialized to false, subscribe to the promise and set the boolean true when the promise is resolved, then assert the boolean is true, does this cover the test case?
Ok I figured it out! Following @pawooten's suggestion, I created a local boolean variable. However, to make the test fail if the code doesn't wait for the promise to resolve, I had to add an asynchronous element to the mock Promise, like this:
let promiseResolved = false;
someAPI.mockImplementation(
() =>
new Promise((resolve) => {
setTimeout(() => {
promiseResolved = true;
resolve();
}, 1000);
})
);
expect(promiseResolved).toBe(true)