我有一段代码,如果连接中断,它会尝试重新连接到Redis。如果它无法重新建立连接,则会抛出错误。我正在尝试测试抛出错误的代码块,但我无法使用mocha和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但是在异步抛出之前失败了。由于同样的原因,try / catch块也会失败。我的猜测是mocha捕获异常并重新抛出它,因为uncaughtException块确实得到错误,但是在mocha失败测试之前没有。有什么建议吗?
编辑:
我曾尝试在一个函数中包装调用:
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
答案 0 :(得分:1)
你在错误回调中调用'done()',所以看起来你可以断言你的错误。如果没有,请将调用包装在另一个函数中:
var fn = function () {
redisClient.resetConnection(c, 2, 100, function (err) { ...}
});
assert.throw(fn, /unable to re-establish connection/)