2014-01-24 57 views
9

我有以下正在編寫集成測試的路由(快速)。使用Sinon-Chai時失敗的測試顯示「錯誤:超過2000ms的超時時間」

下面的代碼:

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交互的存根。

我用的柴,興農和興農柴和摩卡作爲測試運行。

這裏的測試代碼:

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

如果寫入該響應(回覆於)參數相匹配的測試通過確定。問題是,當測試失敗的失敗消息是:

「錯誤:2000毫秒的超時超標」

我引用this answer,但它並沒有解決問題。

我怎樣才能得到這個代碼,以顯示正確的測試名稱和失敗的原因?

NB次要問題可能是,可以在響應對象被斷言的方式在改進?

回答

14

該問題看起來像是一個異常吞噬某處。這使我想到的第一件事就是在你的諾言鏈的末端添加done

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

它與你想通過調用這樣的方法來結束你的諾言鏈工作時通常是這種情況。有些實現稱它爲done,有些稱它爲end

How can I get this code to display the correct test name and the reason for failure?

如果摩卡從未看到外,沒有什麼可以做給你一個不錯的錯誤消息。診斷可能的吞嚥異常的一種方法是在有問題的代碼周圍添加try ... catch塊並將某些內容轉儲到控制檯。

+0

.done()解決了它!我怎麼錯過了!?謝謝。 –

+1

運行500多個規格時出現此錯誤的案例有何想法? –

+0

>某處出現異常情況 – givanse

相關問題