Using Node.js, sinon-chai, and proxyquire for injection.
I have a function that calls fetch. When the fetch promise is full fulled, it calls another function that calls a second fetch.
How do I stub fetch to where I can assert it twice? Right now, I can only assert it once when it has been called twice.
index.js
sendAlert = require('alerts').sendAlert;
function init() {
fetch(darkWeatherUrl)
.then(()> {
sendAlert();
});
}
alerts.js
function sendAlert() {
fetch(request)
.then(...)
}
test
describe('lifx alert test', ()=> {
var fetchStub1;
beforeEach(() => {
fetchStub1 = sinon.stub();
});
it('fetch should of called twice', ()=> {
var body = {
"hourly": {
data:
[ { time: 1493413200,
icon: 'clear-day',
precipIntensity: 0,
precipProbability: 0,
ozone: 297.17 }]
}
};
var response = { json: () => { return body } };
fetchStub1.returns(Promise.resolve(response));
proxy('../index.js', {
'node-fetch': fetchStub1
},
{'../alerts' : {
'node-fetch': fetchStub1
}
});
fetchStub1.should.have.been.callCount(2);
});
});
mocha results
1) lifx alert test fetch should of called twice:
expected stub to have been called exactly twice, but it was called once
stub(https://api.darksky.net/forecast/580c/37.267,-12.433) => [Promise] { } at init (/home/one/github/lifx-weather/index.js:23:3)
AssertionError: expected stub to have been called exactly twice, but it was called once
stub(https://api.darksky.net/forecast/5/3.87,-22.43) => [Promise] { } at init (index.js:23:3)
at Context.it (test/foo.js:45:33)