NodeJS – 在process.oncallback中testingunit testingsetTimeout

我正在尝试使用Jest在我的process.on('SIGTERM')callback中testing一个计时器,但是它似乎永远不会被调用。 我正在使用jest.useFakeTimers() ,虽然它似乎将setTimeout调用模拟到一个范围,但它不会在检查setTimeout.mock对象时结束。

我的index.js文件:

 process.on('SIGTERM', () => { console.log('Got SIGTERM'); setTimeout(() => { console.log('Timer was run'); }, 300); }); setTimeout(() => { console.log('Timer 2 was run'); }, 30000); 

和testing文件:

 describe('Test process SIGTERM handler', () => { test.only('runs timeout', () => { jest.useFakeTimers(); process.exit = jest.fn(); require('./index.js'); process.kill(process.pid, 'SIGTERM'); jest.runAllTimers(); expect(setTimeout.mock.calls.length).toBe(2); }); }); 

并且testing失败:

预期值为(使用===):2收到:1,控制台日志输出为:

 console.log tmp/index.js:10 Timer 2 was run console.log tmp/index.js:2 Got SIGTERM 

我如何让setTimeout在这里运行?

可以做的是,嘲笑方法on的进程on以确保你的处理程序将被调用kill方法。

确保这个处理程序将被调用的一个方法是一起模拟kill

 describe('Test process SIGTERM handler', () => { test.only('runs timeout', () => { jest.useFakeTimers(); processEvents = {}; process.on = jest.fn((signal, cb) => { processEvents[signal] = cb; }); process.kill = jest.fn((pid, signal) => { processEvents[signal](); }); require('./index.js'); process.kill(process.pid, 'SIGTERM'); jest.runAllTimers(); expect(setTimeout.mock.calls.length).toBe(2); }); }); 

另一种更普遍的方法是在setTimeout模拟处理程序,并testing如下所示:

index.js

 var handlers = require('./handlers'); process.on('SIGTERM', () => { console.log('Got SIGTERM'); setTimeout(handlers.someFunction, 300); }); 

handlers.js

 module.exports = { someFunction: () => {} }; 

index.spec.js

 describe('Test process SIGTERM handler', () => { test.only('sets someFunction as a SIGTERM handler', () => { jest.useFakeTimers(); process.on = jest.fn((signal, cb) => { if (signal === 'SIGTERM') { cb(); } }); var handlerMock = jest.fn(); jest.setMock('./handlers', { someFunction: handlerMock }); require('./index'); jest.runAllTimers(); expect(handlerMock).toHaveBeenCalledTimes(1); }); });