我试图在我的process.on('SIGTERM')
回调中使用Jest对计时器进行单元测试,但它似乎从未被调用过。我使用的是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);
以及测试文件:
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);
});
});
而测试失败了:
期望值(使用===):2接收:1,控制台日志输出为:
console.log tmp/index.js:10
Timer 2 was run
console.log tmp/index.js:2
Got SIGTERM
如何让setTimeout
在这里运行?
发布于 2017-10-03 03:10:00
可以做的是模拟流程on
方法,以确保在kill
方法上调用处理程序。
确保调用处理程序的一种方法是模拟kill
和on
。
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
中模拟处理程序并进行调用的测试,如下所示:
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);
});
});
https://stackoverflow.com/questions/46494297
复制相似问题