Node.js 在Mocha中测试异步抛出
我有一段代码,在连接中断时尝试重新连接到Redis。如果无法重新建立连接,它将抛出一个错误。我试图测试抛出错误的代码块,但是我无法使用mocha和chai编写成功的测试 我的测试如下所示:Node.js 在Mocha中测试异步抛出,node.js,mocha.js,chai,Node.js,Mocha.js,Chai,我有一段代码,在连接中断时尝试重新连接到Redis。如果无法重新建立连接,它将抛出一个错误。我试图测试抛出错误的代码块,但是我无法使用mocha和chai编写成功的测试 我的测试如下所示: it('throws an error when a connection can\'t be established', function (done) { var c = redisClient.newClient(); c.end(); sin
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/);
var fn = function () {
redisClient.resetConnection(c, 2, 100, function (err) { ...}
});
assert.throw(fn, /unable to re-establish connection/)
我得到以下信息:
✖ 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()”,因此您似乎要在那里断言错误。如果不是,请尝试将调用包装到另一个函数中:
var a = function() {redisClient.resetConnection(c, 2, 100, function () {
done('Should not reach here');
});
};
expect(a).to.throw(/unable to re-establish connect/);
var fn = function () {
redisClient.resetConnection(c, 2, 100, function (err) { ...}
});
assert.throw(fn, /unable to re-establish connection/)