I am currently doing something similar as described in How to stub https.request response.pipe with sinon.js?
Actually I am doing the same but my code is a bit more complex since I have multiple path ways (conditions) regarding the request code handling and use a promise instead of callback. Furthermore, I use the https instead of the request module.
I have currently the following code which I can't get to work:
//utils.js
/**
* Fetches the repository archive
*
* @param url The archive download url
* @param dest The temp directory path
* @param accessToken The access token for the repository (only available if private repository)
*/
exports.fetchArchive = function(url, dest, accessToken) {
let options = {
headers: {}
}
if (accessToken) {
options.headers = {'PRIVATE-TOKEN': accessToken}
}
return new Promise((resolve, reject) => {
https
.get(url, options,(response) => {
const code = response.statusCode;
if (code >= 400) {
reject({ code, message: response.statusMessage });
} else if (code >= 300) {
this.fetchArchive(response.headers.location, dest).then(resolve, reject);
} else {
response
.pipe(fs.createWriteStream(dest))
.on('end', () => resolve(null))
.on('error', () => reject({ code, message: response.statusMessage }));
}
})
});
}
_
//utils.test.js
describe('public fetchArchive', () => {
it(`should have a redirect status code (>= 300) and redirect and thus be called at twice`, () => {
let options = {
headers: {}
}
options.headers = {'PRIVATE-TOKEN': repoPropsPrivate.accessToken}
const mockResponse = `{"data": 123}`;
// //Using a built-in PassThrough stream to emit needed data.
const mockStream = new PassThrough();
mockStream.push(mockResponse);
mockStream.end(); //Mark that we pushed all the data.
sinon
.stub(https, 'get')
.callsFake(function (privateUrl, options, callback) {
callback(mockStream);
return Promise.resolve(null); //Stub end method btw
});
//Finally keep track of how 'pipe' is going to be called
sinon.spy(mockStream, 'pipe');
return utils.fetchArchive(privateArchiveUrl, privateArchiveDest, repoPropsPrivate.accessToken)
.then((res) => {
sinon.assert.calledOnce(mockStream.pipe);
//We can get the stream that we piped to.
let writable = mockStream.pipe.getCall(0).args[0];
assert.equal(writable.path, './output.json');
})
});
});
I am not sure how to adapt the code from the other post to fit my requirements.
I don't know how to send a response including the request code followed by the stream, and furthermore how to process the promise then in the test.
I would really appreciate your help.
Aucun commentaire:
Enregistrer un commentaire