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");
});
});