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?