1
1

More than 3 years have passed since last update.

Jestでカスタムイベントのdispatchを検証する方法

Last updated at Posted at 2020-02-10

Jestでカスタムイベントのdispatchを検証する方法です。
調べてあまり情報出てこなかったのでメモ。

テスト対象

単純にセレクタと、カスタムイベント名を受け取ってイベントを発行する関数を対象とします。

trigger-custom-event.ts
export const triggerCustomEvent = (
  selector: string,
  eventName: string
): void => {
  const target = document.querySelector(selector);
  target?.dispatchEvent(new Event(eventName));
};

テストコード

dispachEventで指定のカスタムイベントが発行されたことを検証するので、対象のDOMのdispachEventをモックに差し替えます。
そして、mockのcallsで発行回数、発行イベント名を検証します。

trigger-custom-event.test.ts
import { triggerCustomEvent } from "../src/trigger-custom-event";

describe("custom actions", () => {
  let spyDispatchEvent: jest.Mock;

  beforeEach(() => {
    spyDispatchEvent = jest.fn();
    const target = document.querySelector("body");
    target!.dispatchEvent = spyDispatchEvent;
  });

  it("カスタムイベントが発行される", () => {
    triggerCustomEvent("body", "customEventName");
    expect(spyDispatchEvent.mock.calls.length).toBe(1);
    expect(spyDispatchEvent.mock.calls[0][0].type).toBe("customEventName");
  });
});
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1