【问题标题】:sinon spy check if function has been called errorsinon spy 检查函数是否被调用错误
【发布时间】:2017-04-02 05:10:51
【问题描述】:

我正在尝试检查是否在我的测试中调用了某个函数。尝试执行此操作时收到错误 TypeError: Cannot read property 'match' of undefined。我已将代码设置为在我的函数上使用sinon.spy(),然后基于此检查callCountgetMarketLabel总是返回一个字符串。以下是我的代码:

beforeEach(() => {
  marketLabelSpy = sinon.spy(getMarketLabel());
}); //please note this is in a describe block but didnt feel it was relevant to post it. marketLabelSpy is pre-defined.

it('should be called', () => {
  expect(marketLabelSpy).to.have.callCount(1);
})

【问题讨论】:

  • getMarketLabel() 返回什么?要附加一个 sinon spy,您需要执行 sinon.spy(func) 或 sinon.spy(object, "method") 或使用 sinon.spy() 作为函数本身。
  • 编辑了原帖。 getMarketLabel 将始终返回 string
  • 我觉得这没什么意义,看看怎么用 sinon spies:sinonjs.org/docs/#spies,没有 sinon.spy 方法取字符串。
  • 我不是在谈论真正的间谍。所以,我想对函数getMarketLabel() 使用间谍来检查该函数是否已被实际调用。

标签: javascript sinon spy


【解决方案1】:

在您的代码中,您正在调用getMarketLabel 函数,函数调用的结果(它是一个字符串)将用于设置您的间谍。这不符合您的预期。

要对函数使用 sinon spy,只需传递对该函数的引用:

beforeEach(() => {
  marketLabelSpy = sinon.spy(getMarketLabel);
});

【讨论】:

  • 好吧,这又近了一步,但是测试没有通过,因为它被调用了 0 次。要调用它,我需要向函数传递一个字符串。
  • getMarketLabel(); expect(marketLabelSpy).to.have.callCount(1);
  • @DevDig 不调用间谍,而是调用原始函数。
  • @robertklep 在这种情况下,spy 是一个包装函数,因此调用 Spy 并由记录调用计数、参数等的 Spy 调用原始函数。
  • @DevDig 当您按照评论中的建议调用 getMarketLabel() 时,您调用的是原始函数,而不是间谍 (jsbin)。
猜你喜欢
  • 1970-01-01
  • 2017-02-12
  • 2018-01-25
  • 2016-12-23
  • 1970-01-01
  • 1970-01-01
  • 2017-04-21
  • 1970-01-01
  • 2017-09-24
相关资源
最近更新 更多