我有以下路线(快速),我正在为其编写集成测试。
代码如下:
var q = require("q"),
request = require("request");
/*
Example of service wrapper that makes HTTP request.
*/
function getProducts() {
var deferred = q.defer();
request.get({uri : "http://localhost/some-service" }, function (e, r, body) {
deferred.resolve(JSON.parse(body));
});
return deferred.promise;
}
/*
The route
*/
exports.getProducts = function (request, response) {
getProducts()
.then(function (data) {
response.write(JSON.stringify(data));
response.end();
});
};我想测试所有组件是否协同工作,但使用的是一个假的HTTP响应,因此我为请求/http交互创建了一个存根。
我使用Chai,Sinon,Sinon-Chai和Mocha作为测试跑步者。
下面是测试代码:
var chai = require("chai"),
should = chai.should(),
sinon = require("sinon"),
sinonChai = require("sinon-chai"),
route = require("../routes"),
request = require("request");
chai.use(sinonChai);
describe("product service", function () {
before(function(done){
sinon
.stub(request, "get")
// change the text of product name to cause test failure.
.yields(null, null, JSON.stringify({ products: [{ name : "product name" }] }));
done();
});
after(function(done){
request.get.restore();
done();
});
it("should call product route and return expected resonse", function (done) {
var writeSpy = {},
response = {
write : function () {
writeSpy.should.have.been.calledWith("{\"products\":[{\"name\":\"product name\"}]}");
done();
}
};
writeSpy = sinon.spy(response, "write");
route.getProducts(null, response);
});
}); 如果写入响应的参数(response.write)匹配,则测试通过ok。问题是,当测试失败时,失败消息是:
“错误:超过2000ms的超时时间”
我引用了this answer,但是它不能解决这个问题。
如何使此代码显示正确的测试名称和失败原因?
注意:第二个问题可能是,断言响应对象的方式是否可以改进?
发布于 2014-01-24 23:09:13
这个问题看起来像是某个地方的异常被吞噬了。我想到的第一件事就是在你的promise链的末尾添加done:
exports.getProducts = function (request, response) {
getProducts()
.then(function (data) {
response.write(JSON.stringify(data));
response.end();
})
.done(); /// <<< Add this!
};通常情况下,当使用promises时,您希望通过调用下面这样的方法来结束链。一些实现称其为done,一些实现称其为end。
如何使此代码显示正确的测试名称和失败原因?
如果Mocha永远看不到异常,那么它就无法给您一个漂亮的错误消息。诊断可能被吞噬的异常的一种方法是添加一个try...在违规代码周围捕获块,并将某些内容转储到控制台。
https://stackoverflow.com/questions/21335702
复制相似问题