【问题标题】:What to do with setTimeout on server stop or jest test end服务器停止或玩笑测试结束时如何处理setTimeout
【发布时间】:2022-11-27 03:00:00
【问题描述】:
我有一个超时,在 api 请求 POST /api/exchange-refresh-token 上运行一个查询以延迟删除使用过的刷新令牌(需要延迟以允许在短时间内进行多次交换)。在运行笑话测试时,我得到了一个错误Jest did not exit one second after the test run has completed,因为这个setTimeout
setTimeout(() => { removeRefreshToken(id).catch(err=>log(err)) }, 5000)
这个问题迫使我思考,我应该如何处理这个setTimeout才能在服务器停止或开玩笑测试结束时不延迟地运行它(或跳过它)?在这种情况下,处理计时器的正确方法是什么?
【问题讨论】:
标签:
javascript
node.js
settimeout
fastify
【解决方案1】:
您可以使用 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