I am trying to unit test a timer using Jest in my process.on('SIGTERM')
callback but it never seems to be called. I am using jest.useFakeTimers()
and while it does seem to mock the setTimeout
call to an extent, it doesn't end up in the setTimeout.mock
object when checking it.
My index.js file:
process.on('SIGTERM', () => {
console.log('Got SIGTERM');
setTimeout(() => {
console.log('Timer was run');
}, 300);
});
setTimeout(() => {
console.log('Timer 2 was run');
}, 30000);
and the test file:
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);
});
});
and the test fails:
Expected value to be (using ===): 2 Received: 1 and the console log output is:
console.log tmp/index.js:10
Timer 2 was run
console.log tmp/index.js:2
Got SIGTERM
How do I get the setTimeout
to be run here?
What can be possible done, is to mock the processes on
method to make sure your handler will be called on kill
method.
One way to make sure the handler will be called is to mock kill
alongside 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);
});
});
Other way, a more general one, is to mock the handler within a setTimeout
and test that is has been called like following:
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);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With