Gambit2007
Gambit2007

Reputation: 3968

Sinon .callsFake() is not mocking the return of the function

I have the following code in my test file:

const stub1 = sinon.stub('../path/to/module', '_myFunc');
stub1.callsFake(function() {
  console.log('223344');
});

Inside a beforeEach in Mocha, but when _myFunc gets called, it is not executing the console.log.

_myFunc is exported like this:

module.exports = {
  _myFunc
}

What am i doing wrong?

Upvotes: 0

Views: 3995

Answers (1)

Lin Du
Lin Du

Reputation: 102257

Here is a working example:

index.ts:

function _myFunc() {
  console.log('real implementation');
}
module.exports = {
  _myFunc
};

index.spec.ts:

import { expect } from 'chai';
import sinon from 'sinon';

const mod = require('./index');

describe('mod', () => {
  it('should stub function', () => {
    const stub = sinon.stub(mod, '_myFunc').callsFake(() => {
      console.log('223344');
    });
    mod._myFunc();
    expect(stub.calledOnce).to.be.true;
  });
});

Unit test result:

  mod
223344
    ✓ should stub function


  1 passing (8ms)

Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57044971

Upvotes: 1

Related Questions