unit testing与Mocha,Chai和Sinon的Node.js应用程序

我是unit testingNode.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*/ }); }); 

我想unit testing代码,特别是使用Sinon间谍,存根和模拟。 例如间谍createInterface,和“closures”事件的callback只被调用一次。 类似地,“行”事件的callback被称为对应于csv中行数的次数。 另外,如果在开发期间不存在CSV如何模拟CSV?

我尝试的一个testing是,但不知道这是否是正确的方法:

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

有关适当的unit testing,以使该代码健壮的其他build议将不胜感激。

当你试图testing你的模块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); }); });