如何等待 vue-test-utils 中已安装组件的发出事件

问题描述 投票:0回答:1

假设我有一个 vue 组件,它在准备好时发出一个事件(例如 AG Grid):

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

在使用 vue-test-utils 测试此组件时如何等待此事件发出?

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

  // ...wait for event to be emitted...
});
vue.js jestjs ag-grid vue-test-utils vitest
1个回答
0
投票

目前,我使用以下辅助方法完成了这项工作,可以等待。它检查包装器是否已发出指定的事件。当发出时,它会解析返回的 Promise,否则它会等待一小会儿并重试:

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

测试可以使用这个实用方法等待emit,然后再继续测试

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

  await ensureEmittedEvent(wrapper, "gridReady");

  // ...continue testing
});
© www.soinside.com 2019 - 2024. All rights reserved.