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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.