BryGom
BryGom

Reputation: 699

How to Test process.on for unhandled rejection

I understand how i can enter in a process of type unhandle rejection using a promise. in my index.js i have this lines:

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

I need coverage in unit test the before process, how can i do that?

my test:

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

        done();
    });
});

Upvotes: 1

Views: 6115

Answers (1)

Samuel Goldenbaum
Samuel Goldenbaum

Reputation: 18939

You can use the following test which should throw, but pass the test:

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

Upvotes: 4

Related Questions