0

我正在努力解决一个非常微不足道的问题。我能够在所有依赖包中存根函数,它工作得很好,但是当我尝试存根我自己的函数时,我似乎无法让它工作。请参阅以下简单示例:

测试.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'
  }
4

1 回答 1

1

我认为你的做法是对的。

例如,我做了如下,

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

结果

  myFunction
    ✓ should stub


  1 passing (12ms)
于 2017-05-29T11:37:03.600 回答