本文介绍了使用Mocha,Chai和Sinon对Node.js应用程序进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是单元测试Node.js应用程序的新手。我的应用程序经过过滤后将CSV文件转换为JSON。

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

我想对代码进行单元测试,尤其是使用Sinon间谍,存根和模拟。例如,侦探createInterface和 close事件的回调仅被调用一次。类似地,行事件的回调被称为与csv中的行数相对应的次数。
另外,如果开发期间不存在CSV,该如何模拟呢?

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.

推荐答案

在尝试测试模块需要 d的模块时,您可能希望使用类似之类的方法来重新布线 require调用。

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

这篇关于使用Mocha,Chai和Sinon对Node.js应用程序进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:14