【问题标题】:Sinon Spy to check function has been calledSinon Spy 检查功能已被调用
【发布时间】:2016-11-21 10:17:25
【问题描述】:

我正在尝试使用sinon.spy() 来检查某个函数是否已被调用。该函数称为getMarketLabel,它返回marketLabel 并将其接受到函数中。我需要检查 getMarketLabel 是否已被调用。我实际上在一个地方打电话给getMarketLabel,就像这样: {getMarketLabel(sel.get('market'))} 我到目前为止的代码是:

describe('Check if it has been called', () => {
  let spy;
  beforeEach(() => {
    spy = sinon.spy(getMarketLabel, 'marketLabel');
  })
  it('should have been called', () => {
    expect(spy).to.be.calledWith('marketLabel');
  });
});

这是我收到的错误: TypeError: Attempted to wrap undefined property marketLabel as function

【问题讨论】:

    标签: javascript testing mocha.js sinon


    【解决方案1】:

    Sinon 不能监视不是某个对象的属性的函数,因为 Sinon 必须能够用该函数的监视版本替换原始函数 getMarketLabel

    一个工作示例:

    let obj = {
      getMarketLabel(label) {
        ...
      }
    }
    sinon.spy(obj, 'getMarketLabel');
    
    // This would call the spy:
    obj.getMarketLabel(...);
    

    这种语法(与您使用的接近)也存在:

    let spy = sinon.spy(getMarketLabel);
    

    但是,这只会在显式调用spy() 时触发间谍代码;当你直接调用getMarketLabel()时,根本不会调用间谍代码。

    另外,这也不起作用:

    let getMarketLabel = (...) => { ... }
    let obj            = { getMarketLabel }
    sinon.spy(obj, 'getMarketLabel');
    
    getMarketLabel(...);
    

    因为你还是直接打电话给getMarketLabel

    【讨论】:

    • @DaveDavidson sinon.spy(getMarketLabel, 'marketLabel') 无效:getMarketLabel 不是对象,marketLabel 不是函数。
    【解决方案2】:

    这是我收到的错误:TypeError: Attempted to wrap undefined property marketLabel as function

    你需要在你的测试文件中引入helper.js,然后在需要的模块上替换相关方法,最后调用被spy替换的方法:

    var myModule = require('helpers'); // make sure to specify the right path to the file
    
    describe('HistorySelection component', () => {
      let spy;
      beforeEach(() => {
        spy = sinon.stub(myModule, 'getMarketLabel'); // replaces method on myModule with spy
      })
      it('blah', () => {
        myModule.getMarketLabel('input');
        expect(spy).to.be.calledWith('input');
      });
    });
    

    您无法测试是否使用helpers.sel('marketLabel') 调用了间谍,因为此函数将在进行测试之前执行。因此,您将通过写作:

    expect(spy).to.be.calledWith(helpers.sel('marketLabel'));

    测试是否使用helpers.sel('marketLabel')(默认为undefined)返回的任何值调用间谍。


    helper.js 的内容应该是:

    module.exports = {
      getMarketLabel: function (marketLabel) {
        return marketLabel
      }
    }
    

    【讨论】:

    • 我不确定帮助文件中应该包含什么。目前这就是我所拥有的:jsfiddle.net/8q1tLhs7 我仍然收到同样的错误。
    • @DaveDavidson:查看更新后的答案。不确定为什么要使用无效语法的 return {getMarketLabel}。我把它改成了return marketLabel
    • 这对我不起作用。我仍然遇到同样的错误。
    • @DaveDavidson:查看更新后的答案。您正在尝试存根该方法。所以你需要使用 sinon.stub()。
    • @rabbitco { getMarketLabel } 是有效的 ES6 语法,它是 { getMarketLabel : getMarketLabel } 的缩写
    猜你喜欢
    • 2017-04-02
    • 2015-11-26
    • 2016-12-23
    • 2017-02-12
    • 2017-09-24
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    相关资源
    最近更新 更多