samedi 29 octobre 2016

Sinon Spy not catching click event

I'm using Mocha and Sinon to test that a click event listener has been added to a button on initialization. The click event is triggered on the button in the test but the spy isn't seeing it.

I can also attach a click event listener inside the test - the spy will catch this but the event is fired twice.

So I'm guessing it's a reference problem - accessing the correct reference to main.myMethod - and spy on that.

Anyone have any idea what I need to do to get this working?

var main = (function() {

    function init() {
      $("#btnGo").on('click', myMethod);
    }

    function myMethod() {
      console.log("myMethod() was called");
      return true;
    }

    init();

    return {
      init: init,
      myMethod: myMethod
    }
  })();


  if (typeof module !== "undefined" && module.exports !== null) {
    module.exports = main;
  }

  /*Test*/

  var expect = require("chai").expect;
  var sinon = require('sinon');
  var jsdom = require("jsdom");
  global.document = jsdom.jsdom('<body></body>');
  global.window = document.defaultView;

  before(() => {
    $ = require("jquery");
    global.$ = $;
  });

  describe("Main.init()", function() {
    it("should attach a click event listener to the button.", function() { 

      $("body").html("<button id='btnGo'>Go</button>");

      var main = require("../src/main.js"), 
        spy = sinon.spy(main, "myMethod");

      $('#btnGo').trigger("click"); 

      sinon.assert.called(spy);  
    });
  });

Aucun commentaire:

Enregistrer un commentaire