簡體   English   中英

如何在摩卡中測試未捕獲的錯誤?

[英]How can I test uncaught errors in mocha?

我想測試以下函數是否按預期執行:

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;
        process.once("uncaughtException", function (error) {
            recordedError = error;
        });

        throwNextTick(error);

        process.nextTick(function () {
            recordedError.should.be(error);
            next();
        });
    });
});

但是mocha似乎想要保留任何錯誤,並且在獲得它們時我的測試失敗:

C:\Users\ddenicola\Programming (Synced)\pubit>mocha test/basicTest.js

  throwNextTick
    0) works as expected

  ? 1 of 1 tests failed:

  1) throwNextTick works as expected:
     Error: boo!
      at Test.fn (C:\Users\ddenicola\Programming (Synced)\pubit\test\basicTest.js:11:21)
      at Test.run (C:\Users\ddenicola\AppData\Roaming\npm\node_modules\mocha\lib\runnable.js:144:15)
      at Runner.runTest (C:\Users\ddenicola\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:271:10)
      at C:\Users\ddenicola\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:315:12
      at next (C:\Users\ddenicola\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:199:14)
      at C:\Users\ddenicola\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:208:7
      at next (C:\Users\ddenicola\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:157:23)
      at Array.0 (C:\Users\ddenicola\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:176:5)
      at EventEmitter._tickCallback (node.js:192:40)

有任何想法嗎?

更新:在下面的評論中提供casey-foster:

從節點v6.0.0開始,您可以使用process.prependOnceListener('uncaughtException', ...)來更簡潔地執行此操作。


老答案:

秘密在於process.listeners('uncaughtException'):

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

只需刪除mocha監聽器,添加自己的,然后重新附加mocha監聽器。

見下文:

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

如果您的異步代碼在域中執行 - 通常就是這種情況 - 您需要更改域上的錯誤偵聽器而不是進程。

為此您可以使用:

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

});

基於timoxley和Casey Foster,在節點v6 ++中

const assert = require('assert')

describe('throwNextTick', function() {
    it('works as expected', function(next) {

        function cb(err) {
            assert.equal(err instanceof Error, true)
            next()
        }

        function test(){
            process.nextTick(() => {
                throw new Error('err')
            })
        }

        process.prependOnceListener('uncaughtException', cb)
        test()

    })
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM