Here's my function, its basically calling an API in a loop with a wait step so I don't hit the rate limit.
import { doAsyncThing } from '../../../somewhere';
export const myAsyncFunc = async () => {
// An array of data
const arrayData = await ['123', '456', '789'];
for (const item of arrayData) {
// Call an API
await doAsyncThing(item);
// Wait for 1 second
await new Promise(resolve => setTimeout(resolve, 1000));
}
};
Here's my test code
jest.mock('../../../somewhere');
jest.useFakeTimers();
test('a test', async () => {
const funcPromise = myAsyncFunc();
jest.runAllTimers();
expect(myAsyncFunc).resolves.toBeUndefined();
expect(doAsyncThing).toBeCalledTimes(2);
expect(setTimeout).toBeCalledTimes(2);
});
However this doesn't work and produces this result
expect(jest.fn()).toBeCalledTimes(expected)
Expected number of calls: 2
Received number of calls: 0
25 | expect(myAsyncFunc).resolves.toBeUndefined();
26 |
> 27 | expect(doAsyncThing).toBeCalledTimes(2);
I'm pretty sure I can't await for myAsyncFunc
to finish as the jest.useFakeTimers
causes me to manually advance timers. However how can I advance timers if myAsyncFunc
is not yet finished?
I'm a bit confused on how to test this function