NodeJS - Jest单元测试process.on回调函数中的setTimeout

9
我正在尝试使用Jest在process.on('SIGTERM')回调中对计时器进行单元测试,但似乎从未被调用。我正在使用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

尝试将sigterm更改为sighup进行测试。可能会导致sigterm终止进程。还可以尝试删除计时器1并检查控制台日志是否以同步方式工作。 - Jehy
1个回答

9

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

确保处理程序被调用的一种方法是同时模拟onkill

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

谢谢你! - Rafael Rozon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接