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?
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();