【问题标题】:How to return fake data from spy.on(obj, 'funcName') when called ?调用时如何从 spy.on(obj, 'funcName') 返回假数据?
【发布时间】:2016-06-19 04:03:09
【问题描述】:

不知道有没有功能! 请问可以吗?

类似的东西:

spy(obj, 'funcName').and.returnValue(5); // spy will return a fake data when 'funcName'called.

我正在使用mochachai-spies

【问题讨论】:

    标签: javascript node.js unit-testing mocha.js chai


    【解决方案1】:

    考虑使用存根来代替间谍。

    根据文档:

    测试存根是具有预编程行为的函数(间谍)。除了可用于更改存根行为的方法之外,它们还支持完整的测试间谍 API。

    存根有一个“返回”方法来做你正在寻找的事情。

    var stub = sinon.stub();
    
    stub.returns(54)
    
    stub(); // 54
    

    【讨论】:

      【解决方案2】:

      看起来他们添加了一个 chai.spy.returns 函数来做到这一点,但 API 对我来说似乎有点奇怪。我安装了lastest code from their master branch 并玩了一些。以下是我的实验:

      var chai = require('chai'),
          spies = require('chai-spies');
      
      chai.use(spies);
      var expect = chai.expect;
      var obj = null;
      
      describe('funcName', function() {
      
        beforeEach(function() {
          obj = {
            funcName: function() {
              return true;
            }
          }
        });
      
        // PASSES
        it('returns true by default', function() {
          expect(obj.funcName()).to.be.true
        });
      
        // PASSES
        it('returns false after being set to a spy', function() {
          var spyFunction = chai.spy.returns(false);
          obj.funcName = spyFunction;
          expect(obj.funcName()).to.be.false
        });
      
        // FAILS
        it('returns false after being altered by a spy', function() {
          chai.spy.on(obj, 'funcName').returns(false);
          expect(obj.funcName()).to.be.false
        });
      
      });
      

      运行这些测试的输出是:

      funcName
        ✓ returns true by default
        ✓ returns false after being set to a spy
        1) returns false after being altered by a spy
      
      
      2 passing (14ms)
      1 failing
      
      1) funcName returns false after being altered by a spy:
         TypeError: Object #<Object> has no method 'returns'
          at Context.<anonymous> (test.js:31:34)
      

      所以看起来他们希望你用返回值实例化一个间谍对象,然后用它替换 obj 上的 funcName 函数。您不能一举监视函数并设置其返回值。

      此外,该功能已添加到 October, 2015 中,此后他们没有发布新版本。我的建议是使用更成熟的库,例如 Sinon.js 用于间谍和存根。您可以使用他们的Stub API 来更改函数的返回值:

      sinon.stub(obj, 'funcName').returns(5);
      

      Stub API 提供了更多改变函数行为的方法,甚至允许您将其替换为完全自定义的函数:

      var func = function() {...}
      
      sinon.stub(obj, 'funcName', func);
      

      【讨论】:

        猜你喜欢
        • 2018-10-11
        • 1970-01-01
        • 1970-01-01
        • 2021-08-24
        • 1970-01-01
        • 2019-11-23
        • 2016-07-26
        • 2023-03-27
        • 1970-01-01
        相关资源
        最近更新 更多