How do you test if an event has been fired in Jasmine without jquery-jasmine
?
I'm working on a project where we don't use jQuery (wohoo), and I'm trying to write a unit test for my menu triggering function. It works like this:
- You click a button
- My testable ponent then runs
document.dispatchEvent(new CustomEvent('menu.toggle'))
- I want to test that the ponent indeed dispatched the custom event.
How do I test this?
How do you test if an event has been fired in Jasmine without jquery-jasmine
?
I'm working on a project where we don't use jQuery (wohoo), and I'm trying to write a unit test for my menu triggering function. It works like this:
- You click a button
- My testable ponent then runs
document.dispatchEvent(new CustomEvent('menu.toggle'))
- I want to test that the ponent indeed dispatched the custom event.
How do I test this?
Share Improve this question edited Aug 7, 2021 at 22:47 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jan 22, 2016 at 2:31 Kris SelbekkKris Selbekk 7,6549 gold badges48 silver badges74 bronze badges1 Answer
Reset to default 11Played around a bit and found a solution that worked well:
import triggerEvent from 'trigger-event';
import ponent from './ponents/site-menu';
describe('triggering menu button', () => {
let menuToggleSpy;
beforeEach(() => {
menuToggleSpy = jasmine.createSpy('event');
ponent();
});
it('dispatches menu.toggle event', () => {
document.addEventListener('menu.toggle', menuToggleSpy);
const $trigger = document.querySelector('.js-trigger-main-menu');
triggerEvent($trigger, 'click');
expect(menuToggleSpy).toHaveBeenCalled();
});
});
Basically create a new spy called 'event', adding it as a event handler for my event, and then verifying it's been called.
If there are better ways to do this, I'll be more than happy to accept a different answer.