I have the following code...
const reqSent = https.get(url, (response) => {
if (response.statusCode == 302 || response.statusCode == 307) {
const url = `https://${reqSent.host}${response.headers.location}`;
NPMServer.sendRequest(url, extract);
} else {
response.pipe(gunzip()).pipe(extract);
};
} ).on("error", ()=>res.status(500).send("Failed"));
I know I can stub with something like...
get = sinon.stub(https, "get")
What I am not sure is how do I get it to call the callback function after? That way I can test these lines...
if (response.statusCode == 302 || response.statusCode == 307) {
const url = `https://${reqSent.host}${response.headers.location}`;
NPMServer.sendRequest(url, extract);
} else {
response.pipe(gunzip()).pipe(extract);
};
CodePudding user response:
I got it it would be...
get = sinon.stub(https, "get")
const item = { ... }
get.getCalls()[0].args[1](item);
CodePudding user response:
The better is use stub.callsArgWith(index, arg1, arg2, ...)
:
Like
callsArg
, but with arguments to pass to the callback.
stub.callsArg(index)
:
Causes the stub to call the argument at the provided index as a callback function.
stub.callsArg(0)
; causes the stub to call the first argument as a callback. If the argument at the provided index is not available or is not a function, a TypeError will be thrown.
const https = require('https');
const sinon = require('sinon');
describe('71862003', () => {
it('should pass', () => {
const item = { statusCode: 200 };
sinon.stub(https, 'get').callsArgWith(1, item);
https.get('https://localhost:3000/api', (response) => {
console.log('response: ', response);
});
sinon.assert.calledWithExactly(https.get, 'https://localhost:3000/api', sinon.match.func);
});
});
Test result:
71862003
response: { statusCode: 200 }
✓ should pass
1 passing (8ms)