Search code examples
javascriptmocha.jssinonsinon-chai

Using sinon how to avoid testing nested function?


I'm using mocha/chai/sino and I'm new with the three of them.

const a = () => {
  b();
}

const b = () => {
  console.log('here');
}

In this example I just want to test that b is been called when calling a without executing b.

Something like:

it('test', () => {
  const spy = sinon.spy(b);
  a();
  chai.expect(spy.calledOnce).to.be.true;
})

Solution

  • Sinon's stub is what you are looking for.

    Sinon Stubs

    When to use stubs? Use a stub when you want to:

    1. Control a method’s behavior from a test to force the code down a specific path. Examples > include forcing a method to throw an error in order to test error handling.

    2. When you want to prevent a specific method from being called directly (possibly because it triggers undesired behavior, such as a XMLHttpRequest or similar).

    it('test', () => {
      const stub = sinon.stub(b);
      a();
      chai.expect(stub.calledOnce).to.be.true;
    })