如果连接中断,我有一段代码会尝试重新连接到 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