Jest/Vue test utils - How to test functions are called when key is pressed?

47 Views Asked by At

I have an event that added using onMounted() method using window.addEventListener. How to test that my method goPrevChannel() or goNextChannel() are called when I press arrow down or arrow up key?

Component.vue

setup: () => {
   function goPrevChannel() {
      // Implementation
   }

   function goNextChannel() {
      // Implementation
   }

   onMounted(() => {
      const listener = (evt: any) => {
        switch (evt.key) {
          case "ArrowDown":
            goNextChannel();
            break;
          case "ArrowUp":
            goPrevChannel();
            break;
        }
      };

      const event = "keydown";
      window.addEventListener(event, listener);
    });
}

This is what I have tried but it doesn't work Component.test.ts

describe("Test", () => {
  test("trigger keydown event", async () => {
    const wrapper = mount(Component);

    const spy = (wrapper.vm.goNextChannel = jest.fn());
    const event = new KeyboardEvent("keydown", { key: "down" });
    document.dispatchEvent(event);
    await wrapper.vm.$nextTick();

    expect(spy).toBeCalled();
  });
})
0

There are 0 best solutions below