NodeJS - Jest unit test setTimeout in the process.on callback

I am trying to use the unit test timer using Jest in my process.on('SIGTERM') callback, but it never seems to be called. I use jest.useFakeTimers() , and although it seems that it makes fun of the setTimeout call a little, it does not fall into the setTimeout.mock object when it is checked.

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 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 (using ===): 2 Received: 1 and console log output:

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

How do I run setTimeout here?

+7
javascript unit-testing jestjs
source share
1 answer

What can be done is to mock on methods to make sure your handler is called by the kill method.

One way to ensure that a handler is called is to have the kill layout next to 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); }); }); 

Another way, more general, is to make fun of the handler in setTimeout , and the test that was called as follows:

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); }); }); 
+4
source share

All Articles