Home > Web Front-end > JS Tutorial > body text

Test a listener is called with expected CustomEvent()

王林
Release: 2024-09-04 16:38:32
Original
670 people have browsed it

Test a listener is called with expected CustomEvent()

Today I realized we had an issue in a test (Jest)

We have a function that emits CustomEvents

In our Jest test, we define a listener and check that it's called with the expected event


I tried changing the detail (the internal object) of the custom event

... and the test was still passing ?

  test('events.voiceEvent() emits "CustomEvent{ lavoiceevent }" event', () => {
    const expectedEvent = new CustomEvent('lavoiceevent', {
      detail: { event: 'USER_SAID_HELLO_ERRRRROR' },
    });

    window.addEventListener('lavoiceevent', listener);
    events.voiceEvent('USER_SAID_HELLO');

    expect(listener).toHaveBeenCalledWith(expectedEvent); // ✅
    expect(listener).toHaveBeenCalledTimes(1);
  });
Copy after login

The problem is this line won't work as expected (its an issue related with the serialization of the Events)

  expect(listener).toHaveBeenCalledWith(expectedEvent)
Copy after login

In order to solve this (and make our test does check the detail of the event) we should use "mock.calls" as:

  test('events.voiceEvent() emits "CustomEvent{ lavoiceevent }" event', () => {
    const listener = jest.fn();
    window.addEventListener('lavoiceevent', listener);

    events.voiceEvent('USER_SAID_HELLO');

    expect(listener).toHaveBeenCalledTimes(1);
    expect(listener).toHaveBeenCalledWith(expect.any(CustomEvent));

    const ev = listener.mock.calls[0][0];
    expect(ev.type).toBe('lavoiceevent');
    expect(ev.detail.event).toBe('USER_SAID_HELLO'); // ? will fail otherwise
  });
Copy after login

--
thanks for reading.

The above is the detailed content of Test a listener is called with expected CustomEvent(). For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!