Catching Mocha timeouts

落爺英雄遲暮 提交于 2020-01-25 04:12:45

问题


I'm writing a node.js web service which needs to communicate with another server. So its basically server to server communication. I don't have any previous experience of writing web services so I have very limited knowledge. For unit tests I'm using Mocha.

Now, I intend to test the behavior of my service for a particular scenario when this other server doesn't respond to my GET request and the request is actually timed out. For tests I've created a fake client and server around my web service. My web service now takes request from this fake client and then gets information from another fake server that I created which then returns the response in the expected format. To simulate timeout I don't do response.end() from my route handler. The problem is that Mocha judges it to have failed this test case.

Is there a way I could catch this intentional timeout in Mocha and the test is a success?


回答1:


As mido22 suggested you should use handle the timeout generated by whatever library you use to connect. For instance, with request:

var request = require("request");

it("test", function (done) {
    request("http://www.google.com:81", {
        timeout: 1000
    }, function (error, response, body) {
        if (error && error.code === 'ETIMEDOUT') {
            done(); // Got a timetout: that's what we wanted.
            return;
        }

        // Got another error or no error at all: that's bad!
        done(error || new Error("did not get a timeout"));
    });
});


来源:https://stackoverflow.com/questions/29162409/catching-mocha-timeouts

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