作者:勿忘 | 来源:互联网 | 2023-02-11 06:34
假设我有以下简单代码:
var https = require('https');
var optiOns= {
host: 'openshift.redhat.com',
port: 443,
path: '/broker/rest/api',
method: 'GET'
};
var req = https.request(options, function(response) {
console.log(response.statusCode);
response.pipe(save stream to file with fs)
});
req.on('error', function(e) {
console.error(e);
});
req.end();
好吧,我对sinon.js有点陌生,我想问一下:如何存入response.pipe()?当然,我可以对https.request进行存根处理并使用.on和.end返回某物很简单,但是我不知道如何测试response.pipe()是否使用适当的参数...(nodejs文档)说响应是回调),在这种情况下,文档无济于事!ofc testing env是mocha,也可以使用chai,请给我一些建议或示例。谢谢,马特
1> Antonio Nark..:
我将您的代码包装到一个接受回调的函数中,因为在当前实现中,我们实际上并不知道管道何时实际完成。因此,假设我们具有如下功能:
const downloadToFile = function (options, callback) {
let req = https.request(options, function (err, stream) {
let writeStream = fs.createWriteStream('./output.json');
stream.pipe(writeStream);
//Notify that the content was successfully writtent into a file
stream.on('end', () => callback(null));
//Notify the caller that error happened.
stream.on('error', err => callback(err));
});
req.end();
};