【问题标题】:How can I stub the following function in sinon?如何在 sinon 中存根以下函数?
【发布时间】:2018-12-08 14:18:12
【问题描述】:

我的测试功能如下:

const testLibrary = require("./test");

describe("Top Test", function() {

    it("should test function", function(done) {
        testLibrary.print();
        done();

    });


});

test.ts 有以下两个功能:

export function stubMe() {
    console.log("original function");
}

export function print() {
    stubMe();
}

当我运行测试时,它会打印:'original function'

我现在尝试按如下方式存根测试:

const testLibrary = require("./test");


const sinon = require("sinon");

const stubMe = sinon.stub(testLibrary, "stubMe");
stubMe.yields();

describe("Top Test", function() {

    it("should test function", function(done) {
        testLibrary.print();
        done();

    });


});

我的测试函数仍然打印“原始函数”,表明该函数没有被存根。

如何存根 stubMe 函数?

更新:

我已经根据下面 Ankit 的解决方案修改了我的代码:

  const sinon = require("sinon");
  const testLibrary = require("./test");

  testLibrary.stubMe();

  const stubMe = new sinon.stub(testLibrary, "stubMe").callsFake(function () {
    console.log("console from stub");
  });

  testLibrary.stubMe();


  describe("Top Test", function () {

    it("should test function", function (done) {
      testLibrary.print();
      done();

    });

  });

奇怪的是,打印出来的是:

original function
console from stub


  Top Test
original function

为什么存根会在测试期间恢复?

【问题讨论】:

  • 因为在一种情况下您调用testLibrary.stubMe(),而在另一种情况下您调用stubMe()。这就是答案所说的。

标签: node.js typescript mocha.js sinon


【解决方案1】:

无法监视或模拟该函数。 stubMe 在同一模块中直接引用。

正如related Jest question 中所解释的,提高可测试性的一种方法是将函数移动到不同的模块:

// one module
export function stubMe() {
    console.log("original function");
}

// another module
import { stubMe } from '...';
export function print() {
    stubMe();
}

在这种情况下,testLibrary.stubMe 可以被窥探或模拟,但前提是使用非原生 ES 模块,因为 ES 模块导出在原生实现中是只读的。

【讨论】:

    【解决方案2】:

    使用callsFake() 而不是yields(),例如:

     const testLibrary = require('./test');
    
      const sinon = require('sinon');
    
      const stubMe = new sinon.stub(testLibrary, 'stubMe');
      stubMe.callsFake(function () {
        console.log('console from stub');
      });
    
      describe('Top Test', function () {
    
        it('should test function', function (done) {
          testLibrary.print();
          done();
    
        });
    
      });
    

    这是上述测试的输出:

    【讨论】:

    • 仍在打印“原始功能”
    • @Hoa 它在我当地对我有用。 sinon是什么版本的?
    • 6.0.1 - 你用的是什么版本?
    • 我正在使用"sinon": "4.2.1"@Hoa
    • 得到一个奇怪的结果 - 请参阅主编辑问题。知道为什么会发生这种行为吗?
    猜你喜欢
    • 1970-01-01
    • 2015-02-12
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多