How can I test uncaught errors in mocha?

前端 未结 3 1573
感情败类
感情败类 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 12:10

    Update: Courtesy of casey-foster in a comment below:

    As of node v6.0.0 you can use process.prependOnceListener('uncaughtException', ...) to do this much more succinctly.


    Old answer:

    The secret lies in process.listeners('uncaughtException'):

    http://nodejs.org/docs/latest/api/events.html#emitter.listeners

    Simply remove the mocha listener, add your own, then reattach the mocha listener.

    See below:

    var assert = require('assert')
    
    function throwNextTick(error) {
        process.nextTick(function () {
            throw error
        })
    }
    
    
    describe("throwNextTick", function () {
        it("works as expected", function (next) {
            var error = new Error("boo!")
            var recordedError = null
            var originalException = process.listeners('uncaughtException').pop()
            //Needed in node 0.10.5+
            process.removeListener('uncaughtException', originalException);
            process.once("uncaughtException", function (error) {
                recordedError = error
            })
            throwNextTick(error);
            process.nextTick(function () {
                process.listeners('uncaughtException').push(originalException)
                assert.equal(recordedError, error)
                next()
            })
        })
    })
    

提交回复
热议问题