How to test document.addEventListener ("keydown", cb) using Mocha & Sinon?

I am trying to find a better way to test 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 would like to make sure that if the keys are modifiers or if the keys are not displayed, nothing will happen if they are there to spy on the self.emit function.

+7
source share
1 answer

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 check the focus window and the click document, for example.

Hope this helps

+1
source

All Articles