在单元测试中对请求NPM模块进行存根响应以测试管道()

时间:2018-03-13 18:35:09

标签: node.js unit-testing express stub npm-request

在我的Express(NodeJS)应用程序中,我正在使用请求库(https://www.npmjs.com/package/request)。我请求的端点触发数据下载,我将其导入本地文件。

function downloadData(filePath) {
    request
      .get(http://endpoint)
      .pipe(fs.createWriteStream(filePath))
      .on('response', function(response) {
         console.log(response);
       })
      .on('finish', () => { console.log("finished!"); })

我的单元测试使用Mocha和Chai。我将文件位置注入要写入,然后从文件中读取以查看是否存在预期数据。

it('should write data to a file', (done) => {
    const requestStub = sinon.stub();
    proxyquire('../../download-data', {
      'request' : requestStub,
    });
    requestStub.returns("Download Succeeded");

    DownloadData.downloadData("./test.json")

    fs.readFile('./test.json', (err, data) => {      
       expect(data.toString()).to.eq("Download Succeeded");
       done();
    });
  });
});

运行时,测试输出为' ' (空字符串)而不是预期的字符串。这意味着我的pipe()未正确写入数据或我的请求存根未返回(或执行)我想要的方式。我的console.log个功能都没有打印(即我没有看到'响应'或者已完成!')。有关如何存根请求以便将少量数据写入文件的想法吗?

提前致谢。

1 个答案:

答案 0 :(得分:0)

这是一个时间问题。

downloadData功能添加回调,并在fs.readFile()完成后执行downloadData测试,例如

function downloadData(filePath, cb) {
  request
    .get(http://endpoint)
    .pipe(fs.createWriteStream(filePath))
    .on('response', function(response) {
       console.log(response);
     })
    .on('error', cb)
    .on('finish', () => { cb(null) })
 }

然后在你的测试中做:

it('should write data to a file', (done) => {
    const requestStub = sinon.stub()
    proxyquire('../../download-data', {
      'request' : requestStub,
    })
    requestStub.returns("Download Succeeded")

    DownloadData.downloadData("./test.json", function (err) {
      fs.readFile('./test.json', (err, data) => {      
        expect(data.toString()).to.eq("Download Succeeded")
        done()
      })
    })
  })
})