【问题标题】:Sinon Spy not catching click eventSinon Spy 没有捕捉到点击事件
【发布时间】:2016-10-29 10:13:08
【问题描述】:

我正在使用 Mocha 和 Sinon 来测试一个点击事件侦听器是否已在初始化时添加到按钮。在测试中的按钮上触发了点击事件,但间谍没有看到它。

我还可以在测试中附加一个点击事件侦听器 - 间谍会捕捉到这个,但该事件会被触发两次。

所以我猜这是一个引用问题 - 访问对 main.myMethod 的正确引用 - 并监视它。

有人知道我需要做什么才能使其正常工作吗?

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

【问题讨论】:

    标签: javascript testing mocha.js sinon jsdom


    【解决方案1】:

    mock jquery .on() 可能更容易达到相同的结果,会更单一。

    没试过,但类似:

    it("", function(){
      var spy = sinon.spy();
      $ = function(){
        return {
          on:spy
        }
      }
    
      sinon.assert.called(spy);
      //test the params as well
    });
    

    【讨论】:

    • 感谢您的回复鲍里斯,但听起来像是一种解决方法,因为它应该可以简单地监视一个方法。我什至通过用 main.myMethod = function() {}; 替换方法 main.myMethod 来尝试一个简单的存根;但仍然没有喜悦——我猜肯定有另一个参考漂浮在某个地方......
    猜你喜欢
    • 2021-07-05
    • 2019-08-25
    • 2012-10-07
    • 2014-07-27
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多