如何使用Mocha& amp;测试document.addEventListener('keydown',cb)兴农?

时间:2016-07-10 05:55:19

标签: javascript-events mocha keyboard-events sinon

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

  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函数。

2 个答案:

答案 0 :(得分:0)

我可以和sinon一起做。这是我的解决方案:

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

希望有所帮助

答案 1 :(得分:0)

尝试一下。

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