javascript - How to mock a module function inside a callback with Sinon.JS? -


i have following javascript code:

import notifications 'notification-system';  export class documentparameters {   handleupload() {     return promise.resolve().then(() => {       notifications.success();     });   } } 

notification-system module installed npm.

i mock notifications.success in unit test:

import notifications 'notification-system'; import { expect } 'chai'; import sinon 'sinon'; import { documentparameters } './document';  describe('handleupload()', () => {   it('should upload , create success notification', (done) => {     const success = sinon.stub(notifications, 'success');     const documentparameters = new documentparameters();      documentparameters.handleupload().then(() => {       expect(success.callcount).to.equal(1);       done();     });      success.restore();   }); }); 

this unit test fails because stub never called: success.callcount 0.

my solution :

import notifications 'notification-system';  export class documentparameters {   handleupload() {     const success = notifications.success;     return promise.resolve().then(() => {       success();     });   } } 

so stub working outside callback not inside. however, told bad practice update original code working unit test.

do know solution not imply change original code?

since upvoted question:

the issue here restore stub success quickly. stub should restored inside promise .then() instead.

the following code work:

import notifications 'notification-system'; import { expect } 'chai'; import sinon 'sinon'; import { documentparameters } './document';  describe('handleupload()', () => {   it('should upload , create success notification', (done) => {     const success = sinon.stub(notifications, 'success');     const documentparameters = new documentparameters();      documentparameters.handleupload().then(() => {       expect(success.callcount).to.equal(1);       success.restore();       done();     });   }); }); 

Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -