接続が切断された場合に 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 ブロックも失敗します。私の推測では、モカが例外をキャプチャして再スローするのは、uncaughtException ブロックがエラーを取得するためですが、モカがテストに失敗する前ではないためです。助言がありますか?
編集:
関数で呼び出しをラップしようとしました:
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