0

I'm struggling with a pretty trivial problem. I am able to stub functions in all dependency packages and it's working great but when I try and stub my own functions I can't seem to get it working. See the following simple example:

test.js:

  var myFunctions = require('../index')
  var testStub = sinon.stub(myFunctions, 'testFunction')
  testStub.returns('Function Stubbed Response')

  ....

  myFunctions.testFunction()  // is original response

index.js:

  exports.testFunction = () => {
    return 'Original Function Response'
  }
Gregg
  • 1,477
  • 1
  • 16
  • 17

1 Answers1

1

I think the way you are doing is right.

For instance, I've done it as below,

index.js

exports.testFunction = () => {
  return 'Original Function Response'
}

index.test.js

const sinon = require('sinon');
const chai = require('chai');
const should = chai.should();
const  myFunctions = require('./index');

describe('myFunction', function () {
  it('should stub', () => {
    sinon.stub(myFunctions, 'testFunction').returns('hello');
    let res = myFunctions.testFunction();
    myFunctions.testFunction.callCount.should.eql(1);
    res.should.eql('hello');
    myFunctions.testFunction.restore();
    res = myFunctions.testFunction();
    res.should.eql('Original Function Response');
  });
});

Result

  myFunction
    ✓ should stub


  1 passing (12ms)
anoop
  • 3,229
  • 23
  • 35
  • thank you anoop for your response, however it is still not working for me. I believe the problem is due to using typescript. I'm not sure why this would be different since all my other 100+ stubs from other dependencies work fine. – Gregg Jun 01 '17 at 21:41
  • 1
    I don't think typescript has anything to do with it. I suspect you may not be restoring any stubs. – anoop Jun 01 '17 at 21:46