问题描述
我正在编写一个node.js Web服务,该服务需要与另一台服务器进行通信.因此,它基本上是服务器到服务器的通信.我以前没有编写Web服务的经验,因此我的知识非常有限.对于单元测试,我使用的是Mocha.
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.
现在,当另一台服务器不响应我的GET请求并且该请求实际上超时时,我打算针对特定情况测试服务的行为.为了进行测试,我在Web服务周围创建了一个伪造的客户端和服务器.现在,我的Web服务从该虚假客户端接收请求,然后从我创建的另一个虚假服务器获取信息,然后以预期的格式返回响应.为了模拟超时,我不从我的路由处理程序中执行response.end().问题是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.
有没有办法可以在Mocha中捕捉到故意的超时,并且测试成功了?
Is there a way I could catch this intentional timeout in Mocha and the test is a success?
推荐答案
如 mido22建议您应该使用处理由您用来连接的任何库生成的超时.例如,使用request
:
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"));
});
});
这篇关于赶上摩卡咖啡超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!