如何测试 process.on 未处理的拒绝

How to Test process.on for unhandled rejection

我了解如何使用 promise 进入 unhandle rejection 类型的过程。 在我的 index.js 我有这样几行:

process.on('unhandledRejection', (result, error) => {
process.exit(1);
}

我需要覆盖之前的单元测试过程,我该怎么做?

我的测试:

describe('Test unhandledRejection', () => {
    it('unhandledRejection ', function runner(done) {
        try {
            const p = Promise.resolve("resolved");
            assert.isRejected(p);
        } catch (error) {
            console.log('unhandledRejection');
        }

        done();
    });
});

您可以使用以下应该抛出的测试,但通过测试:

     it('unhandledRejection ', function runner(done) {
        process.on('unhandledRejection', (reason, promise) => {
            done();
        });

        async function main () {
            try {
                await doesntexist; // . will throw
            }
            catch(err) {
                console.error(err);
                throw err;
            }
        }

        main();
    });