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