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 calling object.method.restore(); (or stub.restore();). exception thrown if property not function, avoid typos when stubbing methods.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -