Unit Test a Node.js application with Mocha, Chai, and Sinon

*爱你&永不变心* 提交于 2019-12-24 07:59:22

问题


I am new to unit testing Node.js application. My application converts CSV file to JSON after some filtering.

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

I want to unit test the code, particularly using Sinon spy, stub, and mock. For example spy that createInterface, and the callback for the "close" event is called only once. Similarly, the callback for the "line" event is called that number of times corresponding to the number of lines in the csv. Also, how to mock the CSV if it's not present during development time?

One test I tried is, but not sure if this is the right way:

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

Additional suggestion on proper unit test to make this code robust will be highly appreciated.


回答1:


As you're trying to test a module that's required by your module, you may wish to use something like rewire to "rewire" the require call.

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


来源:https://stackoverflow.com/questions/41829963/unit-test-a-node-js-application-with-mocha-chai-and-sinon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!