简体   繁体   English

服务器停止或玩笑测试结束时如何处理setTimeout

[英]What to do with setTimeout on server stop or jest test end

I have a timeout that on api request POST /api/exchange-refresh-token run's a query to remove used refresh token with a delay (delay is required to allow multiple exchanges in small timeframe).我有一个超时,在 api 请求POST /api/exchange-refresh-token运行查询以延迟删除使用的刷新令牌(需要延迟以允许在短时间内进行多次交换)。 While running jest tests I got an error Jest did not exit one second after the test run has completed because of this setTimeout在运行玩笑测试时,由于这个setTimeout ,我得到一个错误Jest did not exit one second after the test run has completed

setTimeout(() => { removeRefreshToken(id).catch(err=>log(err)) }, 5000)

That issue forced me to think, what should I do with this setTimeout to run it without delay on server stop or jest test end (or to skip it)?这个问题迫使我思考,我应该如何处理这个setTimeout以在服务器停止或开玩笑测试结束时不延迟地运行它(或跳过它)? What is a proper way to take care of timers in this cases?在这种情况下,处理计时器的正确方法是什么?

You can use jest.useFakeTimers() to fake a timeout like this:您可以使用 jest.useFakeTimers() 像这样伪造超时:

timerGame.js timerGame.js

function timerGame(callback) {
  console.log('Ready....go!');
  setTimeout(() => {
    console.log("Time's up -- stop!");
    callback && callback();
  }, 1000);
}

module.exports = timerGame;

tests /timerGame-test.js测试/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);
});

Have many way to fake a timeout for jet, you can see in here: https://jestjs.io/docs/timer-mocks有很多方法可以为 jet 伪造超时,你可以在这里看到: https://jestjs.io/docs/timer-mocks

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM