1

在我的 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功能都没有打印(即我没有看到“响应”或“完成!”)。关于如何存根请求以将少量数据写入文件的任何想法?

提前致谢。

4

1 回答 1

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()
      })
    })
  })
})
于 2018-03-14T01:54:47.300 回答