[英]Unit Test a Node.js application with Mocha, Chai, and Sinon
我是單元測試Node.js應用程序的新手。 經過過濾,我的應用程序將CSV文件轉換為JSON。
var fs = require('fs');
var readline = require('readline');
module.exports = ((year) => {
if (typeof year !== "number" || isNaN(year)){
throw new Error("Not a number");
}
var rlEmitter = readline.createInterface({
input: fs.createReadStream('./datasmall.csv'),
output: fs.createWriteStream('./data.json')
});
rlEmitter.on('line', function(line) {
/*Filter CSV line by line*/
});
rlEmitter.on('close', function() {
/*Write to JSON*/
});
});
我想對代碼進行單元測試,尤其是使用Sinon間諜程序,存根和模擬程序。 例如,偵探createInterface和“ close”事件的回調僅被調用一次。 類似地,“行”事件的回調被稱為與csv中的行數相對應的次數。 另外,如果在開發期間不存在CSV,該如何模擬它呢?
我嘗試過的一種測試是,但不確定這是否正確:
describe("Test createInterface method of readline", function(err){
it("should be called only once", function() {
var spyCreateInterface = sinon.spy(readline, 'createInterface');
convert(2016);
readline.createInterface.restore();
sinon.assert.calledOnce(spyCreateInterface);
});
我們將高度贊賞有關適當的單元測試以使該代碼更健壯的其他建議。
在嘗試測試模塊所require
的模塊時,您可能希望使用諸如rewire之類的方法來“重新布線” require調用。
var rewire = require("rewire");
var sinon = require("sinon");
var myModule = rewire("path/to/module");
describe("Test createInterface method of readline", function(err){
it("should be called only once", function() {
var readlineStub = sinon.stub();
myModule.__set__("readline", readlineStub);
myModule.convert(2016);
sinon.assert.calledOnce(spyCreateInterface);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.