As I work with a TypeScript async function that requires a 1-second sleep between two statements, this implementation is in place:
async function systemUnderTest(): Promise<void> {
console.log("One");
await new Promise(r => { setTimeout(r, 1000); });
console.log("Two");
}
To test this function within the Jest framework, the following test can be executed:
test('myTest', async () => {
await systemUnderTest();
});
While this test functions using real time, the question arises - How can this function be tested in fake time?
An attempt was made to write the following test for testing in fake time:
test('myTest', async () => {
jest.useFakeTimers();
await systemUnderTest();
jest.runAllTimers();
jest.useRealTimers();
});
However, upon executing this test, it exceeds the 5-second timeout and fails to print "Two".