Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sinon Spy is never called

I am testing a method A which is calling another method B with different arguments based on conditions. So I would want to spy on B so that I can check whether its called. But the spy is never getting called.

import parent from '../something.js'
describe('Testing A', () => {
  it('should make proper calls to B', () => {
      var spy = sinon.spy(parent, 'B')
      parent.A()
      expect(spy.calledOnce).to.be.true
  })
})

and the test function A would just be

export const A = () => {
    B()
}

Seems like in test, spy version of B is never called because A calls B directly. How can I make the test function of A to call the Sinon version of B?

like image 411
Roy Avatar asked Dec 03 '25 10:12

Roy


1 Answers

To me your code is not testable. You should treat module under test as black box and not to try tweak with its internals. In your case you are trying to spy on method that is internal to something.js module.

Pass B as parameter into A:

export const A = (B) => {
    B();
}

In that case it is callback which is very easy to test:

import parent from '../something.js'
describe('Testing A', () => {
  it('should make proper calls to B', () => {
      var B = sinon.spy();
      parent.A(B);
      expect(B.calledOnce).to.be.true;
  })
})
like image 172
luboskrnac Avatar answered Dec 04 '25 22:12

luboskrnac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!