[英]What to do with setTimeout on server stop or jest test end
我有一個超時,在 api 請求POST /api/exchange-refresh-token
運行查詢以延遲刪除使用的刷新令牌(需要延遲以允許在短時間內進行多次交換)。 在運行玩笑測試時,由於這個setTimeout
,我得到一個錯誤Jest did not exit one second after the test run has completed
setTimeout(() => { removeRefreshToken(id).catch(err=>log(err)) }, 5000)
這個問題迫使我思考,我應該如何處理這個setTimeout
以在服務器停止或開玩笑測試結束時不延遲地運行它(或跳過它)? 在這種情況下,處理計時器的正確方法是什么?
您可以使用 jest.useFakeTimers() 像這樣偽造超時:
timerGame.js
function timerGame(callback) {
console.log('Ready....go!');
setTimeout(() => {
console.log("Time's up -- stop!");
callback && callback();
}, 1000);
}
module.exports = timerGame;
測試/timerGame-test.js
jest.useFakeTimers();
jest.spyOn(global, 'setTimeout');
test('waits 1 second before ending the game', () => {
const timerGame = require('../timerGame');
timerGame();
expect(setTimeout).toHaveBeenCalledTimes(1);
expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 1000);
});
有很多方法可以為 jet 偽造超時,你可以在這里看到: https://jestjs.io/docs/timer-mocks
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.