how can I wait" /> how can I wait" /> how can I wait"/>

How can I wait for an emitted event of a mounted component in vue-test-utils

51 Views Asked by At

Suppose I have a vue component which emits an event when ready (AG Grid for example):

<ag-grid-vue
  ...
  @grid-ready="onGridReady"
  ...
/>

how can I wait for this event to be emitted while testing this component with vue-test-utils?

it("should mount correctly", async () => {
  const wrapper = mount(AgGridVue);

  // ...wait for event to be emitted...
});
1

There are 1 best solutions below

0
Philip Bijker On

For now, I got this working with the following helper method which can be awaited. It checks for the wrapper to have emitted a specified event. When emitted, it resolves the returned promise, otherwise it waits a short while and tries again:

const ensureEmittedEvent = (wrapper: VueWrapper, event: string) =>
  new Promise<void>((resolve) => {
    (function waitForCondition() {
      if (wrapper.emitted(event)) {
        // once our condition has been met we can return
        return resolve();
      }

      // condition has not been met yet - wait a bit longer
      setTimeout(waitForCondition, 10);
    })();
  });

The test can use this utility method to wait for the emit, before continuing the test

it("should mount correctly", async () => {
  const wrapper = mount(AgGridVue);

  await ensureEmittedEvent(wrapper, "gridReady");

  // ...continue testing
});