DEV Community

Manuel Artero Anguita 🟨
Manuel Artero Anguita 🟨

Posted on β€’ Edited on

Test that a js-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);
  });
Enter fullscreen mode Exit fullscreen mode

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

  expect(listener).toHaveBeenCalledWith(expectedEvent)
Enter fullscreen mode Exit fullscreen mode

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
  });
Enter fullscreen mode Exit fullscreen mode

--
thanks for reading.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series πŸ‘€

Watch the Youtube series

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay