首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >已调用Sinon Spy to check函数

已调用Sinon Spy to check函数
EN

Stack Overflow用户
提问于 2016-11-21 18:17:25
回答 2查看 2K关注 0票数 1

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

代码语言:javascript
复制
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

EN

回答 2

Stack Overflow用户

发布于 2016-11-21 18:47:32

Sinon不能窥探不是某个对象属性的函数,因为Sinon必须能够将原始函数getMarketLabel替换为该函数的间谍版本。

下面是一个工作示例:

代码语言:javascript
复制
let obj = {
  getMarketLabel(label) {
    ...
  }
}
sinon.spy(obj, 'getMarketLabel');

// This would call the spy:
obj.getMarketLabel(...);

此语法(与您正在使用的语法很接近)也存在:

代码语言:javascript
复制
let spy = sinon.spy(getMarketLabel);

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

此外,这也不会起作用:

代码语言:javascript
复制
let getMarketLabel = (...) => { ... }
let obj            = { getMarketLabel }
sinon.spy(obj, 'getMarketLabel');

getMarketLabel(...);

因为您仍然直接调用getMarketLabel

票数 2
EN

Stack Overflow用户

发布于 2016-11-21 19:09:02

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

您需要将helper.js放入测试文件中,然后替换所需模块上的相关方法,最后调用替换为间谍的方法:

代码语言:javascript
复制
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的内容应该是:

代码语言:javascript
复制
module.exports = {
  getMarketLabel: function (marketLabel) {
    return marketLabel
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40717736

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档