使用Mocha和Chai捕获超出范围的错误

Tre*_*kow 6 javascript mocha.js node.js chai

我正在修改node.js库以支持真正的异步操作.

我和Mocha和Chai在制作这个(类似的)测试通过时遇到了麻烦.

it('should throw an error', function() {
    expect(function() {
        process.nextTick(function() {
            throw new Error('This is my error');
        });
    }).to.throw(Error);
});
Run Code Online (Sandbox Code Playgroud)

问题是 - 由于nextTick - 错误被抛出范围,it除了测试失败之外,Mocha还输出以下内容.

Uncaught Error: This is my error
Run Code Online (Sandbox Code Playgroud)

构建此测试以使其成功的正确方法是什么?

Lou*_*uis 4

嗯......在一个成熟的应用程序中,我要做的可能是使用像Sinon这样的东西来检查应该抛出错误的方法是否已经被调用并且正在抛出。

在无法执行此操作的代码中,以下方法将捕获异常:

var expect = require("chai").expect;
var domain = require("domain");

it('should throw an error', function(done) {
    var d = domain.create();
    d.on('error', function (err) {
        // Exit the current domain.
        d.exit();
        // We must execute this code at the next tick.
        process.nextTick(function () {
            console.log(err); // Just to show something on the console.
            expect(err instanceof Error).to.be.true;
            done();
        });
    });


    d.run(function () {
        process.nextTick(function() {
            throw new Error('This is my error');
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

此代码创建一个存储在d. 域将error在其中发生的未捕获异常时发出事件,因此我们在创建的域 ( ) 内运行测试d.run(...)并等待异常发生 ( d.on('error', ...)。我们检查它是否是一个Error对象。(在实际测试中,我还会检查错误消息。)当我们完成后,我们调用done()告诉 Mocha 异步测试已经结束。

error事件处理程序调用d.exit(). 这是为了让 Mocha 在断言 ( expect(err instanceof Error)...) 失败时能够正常捕获错误。如果我们不退出域,那么域将捕获错误。此外,检查本身必须在域外的下一个刻度时执行d。

使用domain有问题吗?

不!

文档附带了一些关于在运行正在进行的进程(如服务器)时domain捕获未捕获的异常后关闭操作的警告。那么要做的就是清理能清理的东西并尽快退出。然而,在测试中使用与 Mocha 已经在做的没有什么不同。Mocha 捕获异步代码中未处理异常的方法是使用. 在捕获未处理的异常后,Mocha将当前测试标记为失败并继续。然而有关的文档说“不要使用它,而是使用它。如果您确实使用它,请在每个未处理的异常后重新启动您的应用程序!”domainprocess.on('uncaughtException'uncaughtExceptiondomains

因此,任何有使用问题的人domain一开始就不应该使用 Mocha。