Search code examples
javascriptember.jssinon

A sinon.spy function that is called does not state it has been called


I'm trying to mock an EmberJS adapter which has a function that carries out a POST request. My test looks like this:

 test('should post something', async function (assert) {
    let controller = this.owner.lookup('path/to/ach-deposit');
  
    controller.setProperties({
      ...,
      store: {
        adapterFor: () => {
          return {postAchDeposit: sinon.spy()}
        }
      }
    })
    await controller.actions.postAchDepositHandler.call(controller);
    assert.ok(controller.store.adapterFor.call().postAchDeposit.called);

  })

This fails. Stepping into the code of where postAchDeposit is called throws no errors. If I were to change sinon.spy() to sinon.stub().return("Hi") it would return Hi but for whatever reason when I try to see if it has been called, it returns false.

In the debugger after postAchDeposit has been called if I check there using this.get('store').adapterFor('funding/ach-deposit').postAchDeposit.called still it returns false.

What am I missing?


Solution

  • each time adapterFor is called sinon.spy() is called again and so a new spy is created.

    So essentialls:

    controller.store.adapterFor().postAchDeposit !== controller.store.adapterFor().postAchDeposit
    

    You probably should first create your stub and then always pass a reference:

        const postAchDeposit = sinon.spy();
        controller.setProperties({
          ...,
          store: {
            adapterFor: () => {
              return {postAchDeposit}
            }
          }
        });
    
        await controller.actions.postAchDepositHandler.call(controller);
        assert.ok(postAchDeposit.called);