【问题标题】:Stub response for Request NPM module in unit test in order to test pipe()单元测试中请求 NPM 模块的存根响应以测试 pipe()
【发布时间】:2018-03-13 18:35:09
【问题描述】:

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

提前致谢。

【问题讨论】:

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


    【解决方案1】:

    这是一个时间问题。

    为您的downloadData 函数添加回调,并在downloadData 完成后执行fs.readFile() 测试,例如

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-24
      • 2020-04-24
      • 2021-07-15
      • 2014-04-17
      • 1970-01-01
      • 1970-01-01
      • 2013-02-21
      • 1970-01-01
      相关资源
      最近更新 更多