Testing for an Asynchronous throw in Mocha

扶醉桌前 提交于 2020-01-04 03:01:27

问题


I have a block of code that tries to reconnect to Redis if a connection breaks. If it can not re-establish connection, it throws an error. I am trying to test the block of code that throws the error, but I am unable to write a successful test using mocha and chai.

My test looks like this:

    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();
        });
    });

I've tried using the assert().throws but that fails before the asynchronous throw occurs. A try/catch block also fails for the same reason. My guess is that mocha captures the exception and re-throws it because the uncaughtException block does get the error, but not before mocha has failed the test. Any suggestions?

Edit:

I had tried wrapping the call in a function:

var a = function() {redisClient.resetConnection(c, 2, 100, function () {
        done('Should not reach here');
    });
};
expect(a).to.throw(/unable to re-establish connect/);

and I get the following:

✖ 1 of 5 tests failed:
1) RedisClient .resetConnection emits an error when a connection can't be established:
 expected [Function] to throw an error

回答1:


You are calling 'done()' inside your error callback, so it seems like that would be where you would assert your Error. IF not, thry to wrapping the invocation in another function:

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

});

assert.throw(fn, /unable to re-establish connection/)


来源:https://stackoverflow.com/questions/12787235/testing-for-an-asynchronous-throw-in-mocha

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!