3

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?

luboskrnac
  • 23,973
  • 10
  • 81
  • 92
Roy
  • 575
  • 2
  • 8
  • 17

1 Answers1

1

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;
  })
})
luboskrnac
  • 23,973
  • 10
  • 81
  • 92