在Mocha中测试异步抛出 [英] Testing for an Asynchronous throw in Mocha

查看:95
本文介绍了在Mocha中测试异步抛出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码,尝试在连接断开时重新连接到Redis.如果无法重新建立连接,则会引发错误.我正在尝试测试引发错误的代码块,但无法使用mocha和chai编写成功的测试.

I have a block of code that tries to reconnect to Redis if a connection breaks. 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.

我的测试如下:

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

我尝试使用assert().throws,但是在异步抛出发生之前失败.尝试/捕获块也由于相同的原因而失败.我的猜测是,由于uncaughtException块确实获得了错误,所以mocha捕获了异常并重新抛出了异常,但是在mocha使测试失败之前却没有.有什么建议吗?

I've tried using the assert().throws but that fails before the asynchronous throw occurs. A try/catch block also fails for the same reason. 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. Any suggestions?

我曾尝试将调用包装在一个函数中

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/);

我得到以下信息:

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

推荐答案

您正在错误回调中调用'done()',因此好像可以在其中声明错误.如果没有,请尝试将调用包装在另一个函数中:

You are calling 'done()' inside your error callback, so it seems like that would be where you would assert your Error. 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/)

这篇关于在Mocha中测试异步抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆