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:
document.dispatchEvent(new CustomEvent('menu.toggle'))
How do I test this?
Played around a bit and found a solution that worked well:
import triggerEvent from 'trigger-event';
import component from './components/site-menu';
describe('triggering menu button', () => {
let menuToggleSpy;
beforeEach(() => {
menuToggleSpy = jasmine.createSpy('event');
component();
});
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.
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