How can I test uncaught errors in mocha?

前端 未结 3 1571
感情败类
感情败类 2021-02-05 11:09

I would like to test that the following function performs as expected:

function throwNextTick(error) {
    process.nextTick(function () {
        throw error;
           


        
3条回答
  •  有刺的猬
    2021-02-05 11:58

    If your async code is executed within a domain - and that is often the case - you need to change the error listener on the domain instead of the process.

    For that you can use:

    it('should produce an unhandled exception', function (done) {
    
        // Remove Mocha's error listener
        var originalErrorListeners = process.domain.listeners('error');
        process.domain.removeAllListeners('error');
    
        // Add your own error listener to check for unhandled exceptions
        process.domain.on('error', function () {
    
            // Add the original error listeners again
            process.domain.removeAllListeners('error');
            for ( var i = 0; i < originalErrorListeners.length; i+=1 ) {
                process.domain.on('error', originalErrorListeners[i]);
            }
    
            // For the sake of simplicity we are done after catching the unhandled exception
            done();
    
        });
    
        // This would be your async application code you expect to throw an exception
        setTimeout(function () {
            throw new Error();
        });
    
    });
    

提交回复
热议问题