2016-11-18 52 views
0

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

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); 
}) 
+0

是什么getMarketLabel()返回?要附加一个sinon间谍,你需要做sinon.spy(func)或sinon.spy(object,“method”)或者使用sinon.spy()作为函数本身。 – DevDig

+0

编辑原文。 'getMarketLabel'将总是返回一个'字符串' – DaveDavidson

+0

我不认为这是有道理的,请参阅如何使用sinon spies:http://sinonjs.org/docs/#spies,没有sinon.spy方法将字符串。 – DevDig

回答

1

在代码中,您呼叫的getMarketLabel函数和函数调用的结果(这是一个字符串)将被用来建立你的间谍。这不符合你的意图。

为了使用上的功能的兴农间谍简单地传递给函数的引用:

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

好吧,这是更接近一步,但测试不通过,因为它已被称为0次。要调用它,我需要传递一个字符串函数。 – DaveDavidson

+0

'getMarketLabel();期望(marketLabelSpy).to.have.callCount(1);' – DevDig

+0

@DevDig即不调用间谍,但原来的功能。 – robertklep