How to assert stub more than once in recursive call?

878 views
Skip to first unread message

Darin Hensley

unread,
May 1, 2017, 8:20:08 PM5/1/17
to Sinon.JS
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)



Darin Hensley

unread,
May 2, 2017, 4:49:51 PM5/2/17
to Sinon.JS
Or more simply asked.... how can I assert a stubbed function that returns a promise  twice in a single test? I can successfully assert it once, but not twice(even though I verified fetch is called twice in the source code) 

source code:

function foo() {
  fetch
(request)
   
.then((response) => {
       bar
();
   
});
}


function bar() {
  fetch
(request)
   
.then((response) => {
       console
.log('fetch is called twice);
     });
}




test: 

 
  it('fetch should of called twice', ()=> {

   
    fetchStub
= sinon.stub();


   
var body = { response: 200 };



   
var response = { json: () => { return body } };

   
    fetchStub
.returns(Promise.resolve(response));
   
   
// for injection
    proxyquire
('../index.js', {
       
'node-fetch': fetchStub
     
}
   
});

    fetchStub
.should.have.been.callCount(2);
 
});

Reply all
Reply to author
Forward
0 new messages