9

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?

shiznatix
  • 1,087
  • 1
  • 20
  • 37
  • Try changing sigterm to sighup for a test. It is possible that sigterm kills the process. Also try to remove timer 1 and check if console log actually worked in a sync way. – Jehy Oct 03 '17 at 07:44

1 Answers1

9

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);
    });
});
cinnamon
  • 240
  • 1
  • 9