Sinon js AssertError: expected stub to be called once but was called 0 times
Asked Answered
A

1

7

I have been learning Sinon JS for unit testing, and I am trying to get this example code working. I have a simple "external" library created:

class MyLib {

   simpleMethod () {
      return 'some response';
   }

   static handler() {
      const myLib = new MyLib();
      myLib.simpleMethod();
   }
}

module.exports = MyLib;

Then, I have a simple test suite:

const chai = require('chai');
const sinon = require('sinon');
const MyLib = require('./my-lib');

describe ('sinon example tests', () => {

  it ('should call simpleMethod once', () => {
     let stubInstance = sinon.stub(MyLib, 'simpleMethod');

     MyLib.handler();

     sinon.assert.calledOnce(stubInstance);
  });

});

But I am returned with the error "AssertError: expected stub to be called once but was called 0 times". I know this is probably obvious, but why is simpleMethod not being called?

Assemble answered 5/6, 2018 at 1:13 Comment(0)
S
7

simpleMethod is an instance method. To stub an instance method, you should stub the prototype.

Try this in your code.

myStub = sinon.stub(MyLib.prototype, 'simpleMethod');

Remember to restore the stub at the end of the test.

myStub.restore();
Subglacial answered 5/6, 2018 at 1:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.