Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing if an event has been triggered in Jasmine

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 component then runs document.dispatchEvent(new CustomEvent('menu.toggle'))
  • I want to test that the component indeed dispatched the custom event.

How do I test this?

like image 593
Kris Selbekk Avatar asked Jan 22 '16 02:01

Kris Selbekk


1 Answers

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.

like image 154
Kris Selbekk Avatar answered Sep 19 '22 10:09

Kris Selbekk