I'm writing a unit test which tests a function which waits a timeout before continuing, I've tried using
jest.useFakeTimers();
jest.advanceTimersByTime(20000);
but I keep getting an error message:
: Timeout - Async callback was not invoked within the 20000 ms timeout specified by jest.setTimeout.Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error:
Module file:
async function main()
{
const promisesArray: Promise<void>[] = [];
// lots of logic and async calls //
for (const userRecord of records) {
promisesArray.push(verifyUserRecord(userRecord.userId));
}
await Promise.all(promisesArray);
}
function waitTimeout(ms: number) {
return new Promise((resolve) => setTimeout(() => resolve(true), ms));
}
async function verifyUserRecord(userId) {
await waitTimeout(CHECK_EXECUTION_STATUS_TIMEOUT);
await <some other method call>
/////////////// more logic /////////////
}
Test File
describe('main test', () => {
beforeAll(() => {
// calls to jest spy on //
});
beforeEach(() => {
jest.useFakeTimers();
// various mocks //
});
afterEach(() => {
jest.resetAllMocks();
});
afterAll(() => {
jest.useRealTimers();
jest.restoreAllMocks();
});
it('Should successfully run', async () => {
const p = main();
jest.advanceTimersByTime(60000);
jest.runAllTimers(); // <- explicitly tell jest to run all setTimeout, setInterval
jest.runAllTicks(); // <- explicitly tell jest to run all Promise callback
await p;
// validations //
});
});
But when I call main method from the test file, I get the error above.
When debugging I see that it arrives to waitTimeout and then either waits or moves on to next it in the test module.
It does not mock the timeout, and continues the module file logic.
How can I properly test the file and mock the timeout?
Thanks in advance.
