4

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

1 回答 1

1

你在你的错误回调中调用'done()',所以看起来你会断言你的错误。如果不是,请尝试将调用包装在另一个函数中:

var fn = function () {
    redisClient.resetConnection(c, 2, 100, function (err) { ...}

});

assert.throw(fn, /unable to re-establish connection/)
于 2012-10-09T02:34:58.810 回答