繁体   English   中英

使用Mocha,Chai和Sinon对Node.js应用程序进行单元测试

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM