我想测试一个函数 setTimeout
内部一个承诺。 然而,它保持时序。
这是功能:
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");
}
};
这是我的测试:
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");
});
问题是,当我尝试运行这个测试失败,并给出了这样的信息:
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."
我已经试过了 jest.setTimeout(10000)
这只会引发错误的 Exceeded timeout of 10000ms ...
任何主意,为什么本事? 或如何解决这个问题?
谢谢!