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.
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"); });
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.
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.
Definition and Usage. The addEventListener() method attaches an event handler to a document.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With