Search code examples
vue.jsvue-composition-apivitestcomposable

How to test if a Vue 3 composable emits the correct event


I have a Vue 3 composable that returns a function emitting an event with a payload. I want to unit test with vitest whether the event is emitted when calling the composable's function and if the payload contains the correct data. Here is an example of the composable:

interface Emits {
  (e: "customEvent", payload: number): void;
}

export function useDemo(emit: Emits) {
  function demoFunction() {
    emit("customEvent", 42);
  }

  return {
    demoFunction,
  };
}

I need a way to test if by calling demoFunction() the event customEvent is emitted with the data 42.


Solution

  • Since emit is predictable in a way it works, the implementation of unit can be tested instead of the behaviour it produces with Vue events:

    let emit = vi.fn();
    let { demoFunction } = useDemo(emit);
    demoFunction();
    expect(emit).toBeCalledWith("customEvent", 42);