在单元测试中请求 NPM 模块的存根响应,以便测试 pipe()



在我的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!"); })

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

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

提前谢谢。

这是一个计时问题。

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

最新更新