Am încercat să testeze o funcție care are setTimeout
în interiorul o promisiune. Cu toate acestea se păstrează calendarul afară.
Aceasta este funcția:
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");
}
};
Și acest lucru este testul meu:
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");
});
Problema este că atunci când am încercați să executați această încercare eșuează și dă acest mesaj:
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."
Am încercat jest.setTimeout(10000)
care doar aruncă o eroare de Exceeded timeout of 10000ms ...
Orice idee de ce se întâmplă acest lucru? Sau cum să o rezolvi?
Multumesc!!!