Search code examples
javascriptmocha.jssinonchaikarma-mocha

Spy on function that's called on click event


What am I doing wrong? Trying to spy on a function that get's called on the elements click event but the test always returns false.

spec:

describe('button', function() {
  before(function() {
    this.spy = sinon.spy(window, 'testMethod');
  });

  it('Should call testMethod', function() {
    $('#testBtn').click();

    expect(this.spy.called).to.equal(true);
  });
});

js:

$('#testBtn').on('click', testMethod);

function testMethod() {
  return true;
}

Solution

  • The problem is due to the fact that this line:

    $('#testBtn').on('click', testMethod);
    

    grabs a reference to testMethod before the spy is set. So it grabs a reference to the original function, not the spy, and then it does not matter that you set a spy on window.testMethod because the function called on a click event is always going to be the original testMethod. You have a few options to get your test to work:

    1. Run $('#testBtn').on('click', testMethod); after you set the spy. For instance, you could put it in your before hook.

    2. Change $('#testBtn').on('click', testMethod); to $('#testBtn').on('click', function () { testMethod(); });. The anonymous function will grab a new reference to testMethod every time a click event is handled. So it will grab a reference to the spy, once you set it.

    I've tested what I'm saying here by creating a test that replicates your code and using the two fixes above.