2016-01-05 97 views
0

我正嘗試在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函數返回真要把它傳遞給測試?我試圖使用承諾,但它也沒有工作。在這種情況下,我應該把回報聲明放在then回調中嗎?什麼是最好的方法?

+0

摩卡支持[異步API(HTTP:/ /mochajs.org/#asynchronous-code)和[Promises](http://mochajs.org/#working-with-promises) – laggingreflex

回答

0

您應該模擬request函數。您可以使用例如sinon存根(爲此提供了returns函數來定義返回值)。

一般 - 單元測試的想法是分離特定功能(測試單元)和存根所有其他的依賴,你應該request :)

做要做到這一點,你必須覆蓋原來的request對象,例如:

before(function() { 
    var stub = sinon.stub(someObjectThatHasRequestMethod, 'request').returns(true); 
}); 

和運行測試後,你應該unstub此對象一樣,將來的測試:

after(function() { 
    stub.restore(); 
}); 

而這一切:)你可以用兩隻afterEach/afterbeforeEach/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(); 
}); 

你可以在這裏找到更多的信息:

Mocha - asynchronous code testing