統合テストを書いている次のルート(高速)があります。
コードは次のとおりです。
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) が一致する場合、テストは成功です。問題は、テストが失敗したときの失敗メッセージが次のようになることです。
「エラー: 2000 ミリ秒のタイムアウトを超えました」
この回答を参照しましたが、問題は解決しません。
このコードを取得して、正しいテスト名と失敗の理由を表示するにはどうすればよいですか?
注意: 二次的な質問として、応答オブジェクトがアサートされる方法を改善できますか?