javascript - How to mock dependency classes for unit testing with mocha.js? -
given have 2 es6 classes.
this class a:
import b 'b'; class { somefunction(){ var dependency = new b(); dependency.dosomething(); } }
and class b:
class b{ dosomething(){ // } }
i unit testing using mocha (with babel es6), chai , sinon, works great. how can provide mock class class b when testing class a?
i want mock entire class b (or needed function, doesn't matter) class doesn't execute real code can provide testing functionality.
this is, mocha test looks now:
var = require('path/to/a.js'); describe("class a", () => { var instanceofa; beforeeach(() => { instanceofa = new a(); }); it('should call b', () => { instanceofa.somefunction(); // how test a.somefunction() without relying on b??? }); });
you can use sinonjs create stub prevent real function executed.
for example, given class a:
import b './b'; class { somefunction(){ var dependency = new b(); return dependency.dosomething(); } } export default a;
and class b:
class b { dosomething(){ return 'real'; } } export default b;
the test like:
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'); }); });
you can restore function if necessary using object.method.restore();
:
var stub = sinon.stub(object, "method");
replaces object.method stub function. original function can restored callingobject.method.restore();
(orstub.restore();
). exception thrown if property not function, avoid typos when stubbing methods.
Comments
Post a Comment