最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Testing if an event has been triggered in Jasmine - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 11

Played 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.

发布评论

评论列表(0)

  1. 暂无评论