简体   繁体   English

在Mocha中测试异步投掷

[英]Testing for an Asynchronous throw in Mocha

I have a block of code that tries to reconnect to Redis if a connection breaks. 我有一段代码,如果连接断开,它会尝试重新连接到Redis。 If it can not re-establish connection, it throws an error. 如果它无法重新建立连接,则会抛出错误。 I am trying to test the block of code that throws the error, but I am unable to write a successful test using mocha and chai. 我试图测试抛出错误的代码块,但我无法使用mocha和chai编写成功的测试。

My test looks like this: 我的测试看起来像这样:

    it('throws an error when a connection can\'t be established', function (done) {
        var c = redisClient.newClient();

        c.end();

        sinon.stub(redisClient, 'newClient', function () {
            return { connected: false };
        });
        redisClient.resetConnection(c, 2, 100, function (err) {
            done();
        });
        process.on('uncaughtException', function (err) {
            err.message.should.equal('Redis: unable to re-establish connection');
            done();
        });
    });

I've tried using the assert().throws but that fails before the asynchronous throw occurs. 我尝试过使用assert()。throws但是在异步抛出之前失败了。 A try/catch block also fails for the same reason. 由于同样的原因,try / catch块也会失败。 My guess is that mocha captures the exception and re-throws it because the uncaughtException block does get the error, but not before mocha has failed the test. 我的猜测是mocha捕获异常并重新抛出它,因为uncaughtException块确实得到错误,但是在mocha失败测试之前没有。 Any suggestions? 有什么建议么?

Edit: 编辑:

I had tried wrapping the call in a function: 我曾尝试在函数中包装调用:

var a = function() {redisClient.resetConnection(c, 2, 100, function () {
        done('Should not reach here');
    });
};
expect(a).to.throw(/unable to re-establish connect/);

and I get the following: 我得到以下内容:

✖ 1 of 5 tests failed:
1) RedisClient .resetConnection emits an error when a connection can't be established:
 expected [Function] to throw an error

You are calling 'done()' inside your error callback, so it seems like that would be where you would assert your Error. 你在错误回调中调用'done()',所以看起来你可以断言你的错误。 IF not, thry to wrapping the invocation in another function: 如果没有,希望将调用包装在另一个函数中:

var fn = function () {
    redisClient.resetConnection(c, 2, 100, function (err) { ...}

});

assert.throw(fn, /unable to re-establish connection/)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM