NodeJS - 在回调过程中的Jest单元测试setTimeout

时间:2017-09-29 17:43:12

标签: javascript node.js unit-testing jestjs

我正在尝试在我的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);
    });
});

并且测试失败:

  

预期值(使用===):         2       收稿日期:         1   并且控制台日志输出为:

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

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

如何让setTimeout在这里运行?

1 个答案:

答案 0 :(得分:4)

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

确保调用处理程序的一种方法是在kill旁边模拟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);
    });
});

其他方式,更常见的一种方法是在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);
    });
});