【问题标题】:How to use sinon to replace the same method with two different return values?如何使用 sinon 用两个不同的返回值替换同一个方法?
【发布时间】:2021-09-28 10:45:12
【问题描述】:

我正在单元测试的一个方法在该方法中多次调用具有不同参数的相同辅助方法。为了让我测试我的方法,我想使用 sinon 的 replace 函数将这个辅助方法的返回值替换为我的模拟数据,但是我每次调用该辅助方法时都需要返回不同的模拟数据。我该怎么做?

举个例子:

const obj = {
  foo(num) {
    return 5 + num;
  },
  methodToTest() {
    return foo(1) + foo(2);
  },
};

我想测试一下,如果foo在参数值为1时返回6,而foo在参数值为2时返回7时,methodToTest()是否能正常工作。

我想我正在寻找的是一种根据传入的参数替换 foo 的返回值的方法,例如:

   sinon.replace(obj, 'foo(1)', sinon.fake.returns(6));
   sinon.replace(obj, 'foo(2)', sinon.fake.returns(7));

知道我该怎么做吗?将不胜感激。

【问题讨论】:

    标签: javascript typescript sinon


    【解决方案1】:

    只需创建一个伪造的foo 函数,该函数根据参数动态提供多个返回值。

    例如

    index.js:

    const obj = {
      foo(num) {
        return 5 + num;
      },
      methodToTest() {
        return this.foo(1) + this.foo(2);
      },
    };
    
    module.exports = obj;
    

    index.test.js:

    const obj = require('./');
    const sinon = require('sinon');
    
    describe('68463040', () => {
      it('should pass', () => {
        function fakeFoo(arg) {
          if (arg == 1) {
            return 6;
          }
          if (arg == 2) {
            return 7;
          }
        }
        sinon.replace(obj, 'foo', fakeFoo);
        const actual = obj.methodToTest();
        sinon.assert.match(actual, 13);
      });
    });
    

    测试结果:

      68463040
        ✓ should pass
    
    
      1 passing (3ms)
    
    ----------|---------|----------|---------|---------|-------------------
    File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ----------|---------|----------|---------|---------|-------------------
    All files |      75 |      100 |      50 |      75 |                   
     index.js |      75 |      100 |      50 |      75 | 3                 
    ----------|---------|----------|---------|---------|-------------------
    

    【讨论】:

    • 啊,这正是我所需要的。非常感谢!
    猜你喜欢
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 2016-09-23
    • 2011-10-15
    • 1970-01-01
    • 2012-01-17
    相关资源
    最近更新 更多