Search code examples
javascriptnode.jsmocha.jssinonsinon-chai

Sinon stubbed function is not recognised by chai spy when asserting function call


I have two asynchronous functions that return bluebird promises:

Async1: function() {

  return new Promise(function(resolve, reject) {

    execute(query)
      .then(function(resp) {
      resolve(resp);
    })
      .catch(function(err) {
      reject(err);
    });
  });

}

Async2: function() {

  return new Promise(function(resolve, reject) {

    execute(query2)
      .then(function(resp) {
      resolve(resp);
    })
      .catch(function(err) {
      reject(err);
    });
  });

}

I have another module that invoked these methods like so:

module.exports = Foo {
  Bar: require(./'Bar');
  caller: function() {
    this.Bar.Async1()

      .then(function(resp) {
        this.Bar.Async2()

         .then(function(resp) {
          // do something
      }.bind(this))
   }.bind(this))
  }
}

In my test case i want to check if the Bar.Async2 gets called and i have the following test case that fails:

it('should call Foo.Bar.Async2', function(done) {
var spy;

  sinon.stub(Foo.Bar, 'Async1').returns(
    new Promise(function(resolve) {
      resolve();
    })
  );

  sinon.stub(Foo.Bar, 'Async2').returns(
    new Promise(function(resolve) {
      resolve();
    })
  );

  spy = chai.spy.on(Foo.Bar, 'Async2');
  Foo.caller();
  expect(spy).to.be.called();
  done();
});

I know from console logs that Async2 does get called, so i am wondering why the spy does not pick it up?


Solution

  • I could not resolve this as a work around in the implementation i had to pass a callback in to the controller that only the tests use. From here i can use the callback to test the code.