使用Sinon-Chai时,失败的testing显示“错误:超过2000ms超时”

我有以下路线(快递),我正在编写一个集成testing。

代码如下:

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

我想testing所有的组件一起工作,但与一个虚假的HTTP响应,所以我创build一个存根请求/ http交互。

我使用柴,Sinon,Sinon-Chai和Mocha作为testing跑步者。

以下是testing代码:

 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)的参数匹配testing通过,则ok。 问题是,当testing失败失败的消息是:

“错误:2000毫秒超时”

我已经引用了这个答案 ,但它不能解决问题。

我怎样才能得到这个代码来显示正确的testing名称和失败的原因?

注意:第二个问题可能是,响应对象被声称的方式是否可以改进?

这个问题看起来像是一个exception被吞噬的地方。 我想到的第一件事就是在你的承诺链的最后添加done

 exports.getProducts = function (request, response) { getProducts() .then(function (data) { response.write(JSON.stringify(data)); response.end(); }) .done(); /// <<< Add this! }; 

通常情况下,使用承诺来处理你想通过调用这样的方法来结束你的链。 有些实现称之为done ,有些则称之为end

我怎样才能得到这个代码来显示正确的testing名称和失败的原因?

如果摩卡从来没有看到这个例外,那么就没有办法给你一个很好的错误信息。 一种诊断可能的吞咽exception的方法是在有问题的代码周围添加一个try … catch块并将某些内容转储到控制台。