Sto cercando di testare una funzione che ha setTimeout
all'interno di una promessa. Tuttavia mantiene il timeout.
Questa è la funzione:
export const sleep = async (duration: number): Promise<void> => {
await new Promise<void>((resolve) => {
setTimeout(resolve, duration);
});
if (process.env.NODE_ENV === "test") {
console.log("sleep end");
}
};
E questo è il mio test:
import { sleep } from "../../helpers/utils";
console.log = jest.fn();
jest.useFakeTimers();
test("calls sleep with correct argument and calls console.log", async () => {
const NODE_ENV = "test";
const SLEEP_DURATION = "100";
process.env = { ...process.env, NODE_ENV, SLEEP_DURATION };
const timeoutSpy = jest.spyOn(global, "setTimeout");
await sleep(+SLEEP_DURATION);
jest.runAllTimers();
expect(sleep).toHaveBeenCalledWith(+SLEEP_DURATION);
expect(timeoutSpy).toHaveBeenCalledWith(+SLEEP_DURATION);
expect(console.log).toHaveBeenCalledWith("sleep end");
});
Il problema è che quando cerco di eseguire questo test ha esito negativo e dà questo messaggio:
thrown: "Exceeded timeout of 5000 ms for a test.
Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
Ho provato jest.setTimeout(10000)
che getta un errore di Exceeded timeout of 10000ms ...
Qualche idea del perché questo sta accadendo? O come risolvere il problema?
Grazie!