Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS - Jest unit test setTimeout in process.on callback

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?

like image 271
shiznatix Avatar asked Sep 29 '17 17:09

shiznatix


1 Answers

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);
    });
});
like image 83
cinnamon Avatar answered Sep 29 '22 07:09

cinnamon