【问题标题】:How to test document.addEventListener('keydown', cb) with Mocha & Sinon?如何用 Mocha 和 Sinon 测试 document.addEventListener('keydown', cb)?
【发布时间】:2016-07-10 05:55:19
【问题描述】:

我正在尝试找出测试此方法的最佳方法:

document.addEventListener("keydown", function (event) {
    var modifiers = event.altKey || event.ctrlKey || event.metaKey ||
                    event.shiftKey;
    var mapped    = map[event.which];

    if (!modifiers) {
      if (mapped !== undefined) {
        event.preventDefault();
        self.emit("move", mapped);
      }
    }
  });

我想确保如果键是修饰符或键未映射,则不会发生任何事情,但是,如果它们是,则监视 self.emit 函数。

【问题讨论】:

    标签: javascript mocha.js dom-events sinon keyboard-events


    【解决方案1】:

    我可以用诗乃做到这一点。这是我的解决方案:

    it('adds listener events', function() {
      sinon.spy(document, 'addEventListener')
      sinon.spy(window, 'addEventListener')
    
      expect(document.addEventListener.calledOnce).not.to.be.true
      expect(window.addEventListener.calledOnce).not.to.be.true
    
      subject.myFunc()
    
      expect(document.addEventListener.calledOnce).to.be.true
      expect(window.addEventListener.calledOnce).to.be.true
    })
    

    以我为例,我必须测试窗口 focus 和文档 click

    希望对你有帮助

    【讨论】:

    • 这不是在测试 OP 想要测试的内容。这只是测试是否调用了addEventListener。 OP 想要测试使用addEventListener 添加的事件处理程序的行为。
    • 所以,我对在侦听器上调用的函数进行了另一个单独的测试。这是实现它的更简单方法
    • 是的,答案不正确,应该在 addEventListner 中测试函数。
    【解决方案2】:

    试试这个。

    before(function() {
      // Create stubs to spy on calls without executing the native code
      global.document= {addEventListener: sinon.stub()};
      global.self = {emit: sinon.stub()};
    
      // Execute the function under test
      subject.myFunc();
    
      // Save the callback function
      this.callback = document.addEventListener.getCalls()[0].args[1];
      this.eventType = document.addEventListener.getCalls()[0].args[0];
    });
    
    it('should use appropriate arguments', function() {
      this.eventType.should.eql("keydown");
      this.callback.should.be.a("function");
    });
    
    it('should use a callback that does nothing without a modifier key', function() {
      const eventProxy = {
        which: 97, // "A"
        preventDefault: sinon.stub()
      };
    
      this.callback(eventProxy);
    
      eventProxy.preventDefault.should.not.be.called;
      global.self.emit.should.not.be.called;
    });
    
    it('should use a callback that prevents default with a modifier key', function() {
      const eventProxy = {
        which: 97, // "A"
        shiftKey: true,
        preventDefault: sinon.stub()
      };
    
      this.callback(eventProxy);
    
      eventProxy.preventDefault.should.be.calledOnce.and.calledWith();
      global.self.emit.should.be.calledOnce.and.calledWith('move');
    });
    

    【讨论】:

      猜你喜欢
      • 2017-10-07
      • 2015-12-01
      • 1970-01-01
      • 2017-12-10
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      • 2017-10-08
      • 1970-01-01
      相关资源
      最近更新 更多