我正在嘗試測驗一個包含setTimeout在 Promise 中的函式。但是它一直超時。
這是函式:
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 ...
知道為什么會這樣嗎?或者怎么解決?
謝謝!
uj5u.com熱心網友回復:
這是一個更接近您想要的解決方案。重要的是,您無法await使用假計時器解決承諾,否則它將永遠無法解決。相反,您可以呼叫將sleep函式的回傳值分配給變數,然后運行計時器,然后等待變數。
我還調整了您expect對超時間諜的宣告,因為它需要兩個引數。最后,我洗掉了您對sleep持續時間呼叫的期望,因為您實際上是在測驗中這樣做,因此做出這種斷言似乎不值得。
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");
const sleepFn = sleep( SLEEP_DURATION);
jest.runAllTimers();
// Now that we ran timers we can await the promise resolving
await sleepFn;
// timeout takes two arguments
expect(timeoutSpy).toHaveBeenCalledWith(
expect.any(Function),
SLEEP_DURATION
);
expect(console.log).toHaveBeenCalledWith("sleep end");
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/366890.html
標籤:javascript 单元测试 玩笑 暂停 设置超时
