我如何在node.js中对文件流进行单元测试呢?

时间:2016-11-05 13:44:37

标签: node.js unit-testing stream fs

我的源代码是:

<top (required)>'
/home/ubuntu/hw-acceptance-unit-test-cycle/rottenpotatoes/Rakefile:5:in

我需要编写单元测试以获得接近100%的覆盖率。我的问题是(a)测试似乎太简单了,(b)我如何实际测试单元测试?

1 个答案:

答案 0 :(得分:1)

将评论作为扩展答案发布。

首先,您需要将数据句柄函数提取到另一个模块中,例如data-handler.js(这是你的代码的一个例子,可能会增强看起来更好,但它只是给出了一个想法)

module.exports = {
   handler: (rowData, topCsvStream, otherCsvStream) => {
      if(headerRow.length === 0) {
         // Save header row in CSV's
         headerRow = rowData;
         topCsvStream.write(headerRow);
         otherCsvStream.write(headerRow);
         return;
      }
      if(rowData[2] === 'public' && rowData[5] > 10 && rowData[4] > 9000 && rowData[1].length < 40) {
        // Save to the top_posts file
        topCsvStream.write(rowData);
      } else {
        // Save to the other_posts file
        otherCsvStream.write(rowData);
      }

      // Save to the daily tops
      var postDate = new Date(rowData[6]);
      postDate = new Date(postDate.getYear(), postDate.getMonth(), postDate.getDate());

     if(!dailyTops[postDate] || parseInt(rowData[3]) >    parseInt(dailyTops[postDate][3])) {
        dailyTops[postDate] = rowData;
      }
   },

   end: (topCsvStream, otherCsvStream) => {
      topCsvStream.end();
      otherCsvStream.end();
      writeDailyList(dailyTops, headerRow);
   }
}

在主文件中,您将引用该模块:

const handler = require("./data-handler");

csv
 .fromPath('posts.csv')
 .on("data", (data) => handler.handler(data, topCsvStream, otherCsvStream).on("end", () => handler.end(topCsvStream, otherCsvStream));

现在您的处理程序代码未绑定到流,您可以轻松地在没有它们的情况下进行测试。