[英]Building tests with mocha for async code (request)
我正在嘗試在Node.JS上與Mocha和Chai創建單元測試。 這是要測試的功能的簡化版本:
router.cheerioParse = function(url, debugMode, db, theme, outCollection, _callback2) {
var nberror = 0;
var localCount = 0;
console.log("\nstarting parsing now : " + theme);
request(url, function(error, response, body) {
//a lot of postprocessing here that returns
//true when everything goes well)
});
}
這是我要編寫的測試:
describe('test', function(){
it('should find documents', function(){
assert( true ==webscraping.cheerioParse("http://mytest.com, null, null, null ,null,null ));
});
})
request
函數如何返回true才能通過測試? 我曾嘗試使用諾言,但也沒有用。 在這種情況下,我應該將return語句放在then
回調中嗎? 最好的方法是什么?
您應該模擬request
功能。 你可以使用如sinon
該存根(它們提供returns
來定義返回值函數)。
通常,單元測試的想法是分離特定的功能(測試單元),並對其他依賴項進行存根,就像您對request
所做的那樣:)
為此,您必須覆蓋原始request
對象,例如:
before(function() {
var stub = sinon.stub(someObjectThatHasRequestMethod, 'request').returns(true);
});
在運行測試之后,您應該取消對該對象的存根,以便將來進行這樣的測試:
after(function() {
stub.restore();
});
僅此afterEach/after
:)您可以在afterEach/after
或beforeEach/before
-選擇更適合您的一種。
還有一點需要注意的是-因為您的代碼是異步的,所以您的解決方案可能需要更復雜的測試方式。 您可以提供完整的request
模擬功能,並在返回值時調用done()
回調,如下所示:
it('should find documents', function(done) {
var requestStub = sinon.stub(someObjectThatHasRequestMethod, 'request',
function(url, function (error, response, body) {
done();
return true;
}
assert(true === webscraping.cheerioParse("http://mytest.com, null, null, null ,null,null ));
requestStub.restore();
});
您可以在此處找到更多信息:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.