shi*_*tix 7 javascript unit-testing node.js jestjs
我试图在我的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);
Run Code Online (Sandbox Code Playgroud)
和测试文件:
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);
});
});
Run Code Online (Sandbox Code Playgroud)
并且测试失败:
预期值为(使用===):2已接收:1且控制台日志输出为:
console.log tmp/index.js:10
Timer 2 was run
console.log tmp/index.js:2
Got SIGTERM
Run Code Online (Sandbox Code Playgroud)
如何setTimeout
在这里运行?
可以做的是模拟进程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);
});
});
Run Code Online (Sandbox Code Playgroud)
另一种更通用的方法是在 asetTimeout
和 test 中模拟处理程序,该处理程序已被调用,如下所示:
index.js
var handlers = require('./handlers');
process.on('SIGTERM', () => {
console.log('Got SIGTERM');
setTimeout(handlers.someFunction, 300);
});
Run Code Online (Sandbox Code Playgroud)
handlers.js
module.exports = {
someFunction: () => {}
};
Run Code Online (Sandbox Code Playgroud)
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);
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1224 次 |
最近记录: |