简体   繁体   中英

Sinon Stub in Mocha Not Working

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'
  }

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM