Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test document.addEventListener('keydown', cb) with Mocha & Sinon?

I'm trying to figure out the best way for testing this method:

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

I'd like to ensure that if the keys are modifiers or if the keys are not mapped, nothing happens, however, if they are, to spy on the self.emit function.

like image 430
Detuned Avatar asked Jul 10 '16 05:07

Detuned


People also ask

How do I test a document with addEventListener?

You need to use some concrete event name like for example click - and click on browser page window - eg: window. addEventListener('click', function() { console. log("some_event triggered"); });

What is difference between window addEventListener and document addEventListener?

The document and window are different objects and they have some different events. Using addEventListener() on them listens to events destined for a different object. You should use the one that actually has the event you are interested in.

How will you use the parameters of addEventListener?

With the addEventListener() method you can specify the propagation type by using the "useCapture" parameter: addEventListener(event, function, useCapture); The default value is false, which will use the bubbling propagation, when the value is set to true, the event uses the capturing propagation.

What is document addEventListener?

Definition and Usage. The addEventListener() method attaches an event handler to a document.


1 Answers

I could do it with sinon. Here is my solution:

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

In my case I had to test window focus and document click for example.

Hope it helps

like image 127
lucianosousa Avatar answered Sep 29 '22 11:09

lucianosousa