我正在尝试在process.on('SIGTERM')回调中使用Jest对计时器进行单元测试,但似乎从未调用过它。我正在使用jest.useFakeTimers(),虽然它似乎在一定程度上模拟了setTimeout调用,但在检查它时并没有最终出现在setTimeout.mock对象中。

我的index.js文件:

process.on('SIGTERM', () => {
    console.log('Got SIGTERM');

    setTimeout(() => {
        console.log('Timer was run');
    }, 300);
});

setTimeout(() => {
    console.log('Timer 2 was run');
}, 30000);

和测试文件:
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);
    });
});

并且测试失败:


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

  console.log tmp/index.js:2
    Got SIGTERM

我如何在此处运行setTimeout

最佳答案

可以做的是模拟流程on方法,以确保将在kill方法上调用您的处理程序。

确保将调用处理程序的一种方法是模拟killon

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);
    });
});

另一种更通用的方法是在setTimeout中模拟处理程序并测试已被调用的代码,如下所示:

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);
    });
});

09-20 17:21