How to mock dependency classes for unit testing with mocha.js?
You can use SinonJS to create a stub to prevent the real function to be executed.
For example, given class A:
import B from './b';
class A {
someFunction(){
var dependency = new B();
return dependency.doSomething();
}
}
export default A;
And class B:
class B {
doSomething(){
return 'real';
}
}
export default B;
The test could look like: (sinon < v3.0.0)
describe("Class A", () => {
var InstanceOfA;
beforeEach(() => {
InstanceOfA = new A();
});
it('should call B', () => {
sinon.stub(B.prototype, 'doSomething', () => 'mock');
let res = InstanceOfA.someFunction();
sinon.assert.calledOnce(B.prototype.doSomething);
res.should.equal('mock');
});
});
EDIT: for sinon versions >= v3.0.0, use this:
describe("Class A", () => {
var InstanceOfA;
beforeEach(() => {
InstanceOfA = new A();
});
it('should call B', () => {
sinon.stub(B.prototype, 'doSomething').callsFake(() => 'mock');
let res = InstanceOfA.someFunction();
sinon.assert.calledOnce(B.prototype.doSomething);
res.should.equal('mock');
});
});
You can then restore the function if necessary using object.method.restore();
:
var stub = sinon.stub(object, "method");
Replaces object.method with a stub function. The original function can be restored by callingobject.method.restore();
(orstub.restore();
). An exception is thrown if the property is not already a function, to help avoid typos when stubbing methods.