Search code examples
javascriptsinonspy

sinon spy check if function has been called error


I am trying to check if a function has been called yet in my tests. I receive the error TypeError: Cannot read property 'match' of undefined when trying to do this. I have setup my code to use sinon.spy() on my function and then check the callCount based on this. getMarketLabel will always return a string. Below is my code:

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

Solution

  • In your code, you are calling the getMarketLabel function and the result of the function call (which is a string) will be used to set up your spy. That does not work as you intended.

    To use a sinon spy on a function simply pass a reference to that function:

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