【问题标题】:Sinon Stub in Mocha Not Working摩卡中的诗农存根不工作
【发布时间】:2017-05-28 00:48:12
【问题描述】:

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

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

【问题讨论】:

    标签: javascript mocha.js sinon sinon-chai


    【解决方案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)
    

    【讨论】:

    • 感谢 anoop 的回复,但它仍然不适合我。我相信问题是由于使用打字稿。我不确定为什么这会有所不同,因为我所有其他 100 多个来自其他依赖项的存根都可以正常工作。
    • 我认为 typescript 与它没有任何关系。我怀疑你可能没有恢复任何存根。
    猜你喜欢
    • 2020-08-31
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 2023-03-20
    • 1970-01-01
    相关资源
    最近更新 更多