vitest测试等待vue3组件中onMounted回调的异步完成

vitest test await async completion of onMounted callback in vue3 component

我正在使用 Vitest,并希望在我的组件的 onMounted 生命周期挂钩中等待几个模拟提取的完成:

我的测试:

import { mount } from '@vue/test-utils';
import HelloWorld from './HelloWorld.vue';
import { mockGet } from 'vi-fetch';
import 'vi-fetch/setup';

mockGet('api/welcome-message').willResolve('Welcome message from vitest');
mockGet('api/players').willResolve(['Mario', 'Luigi']);


test('the players have been rendered', async () => {
  const wrapper = mount(HelloWorld);

  const lastPlayer = await wrapper.findAll('.player');
  expect(lastPlayer).toHaveLength(2);
});

我的组件脚本:

<script setup lang="ts">
import { onMounted, ref } from 'vue';

const apiMessage = ref('');
const players = ref<string[]>([]);


onMounted(async () => {
  const fetchMessage = fetch('api/welcome-message')
    .then((res) => res.text())
    .then((message: string) => (apiMessage.value = message));

  const fetchPlayers = fetch('api/players')
    .then((res) => res.json())
    .then((playersRes: string[]) => (players.value = playersRes));
});
</script>

测试失败的原因是,我假设 onMounted 中的代码 运行 在测试查找所有 .player <li> 元素(使用v-for) 关闭 players 参考。我怎样才能让 vitest 在调用测试失败之前等待每个提取的响应。

谢谢。

提取 Promises 在下一个 macro tick 中解析,可以这样等待:

test('...', async() => {
  ⋮
  await new Promise(r => setTimeout(r));
})

或者您可以为此使用 Vue Test Utils' utility

import { flushPromises } from '@vue/test-utils';

test('...', async() => {
  ⋮
  await flushPromises();
})

在 运行 任何断言之前添加该行:

                     
import { mount, flushPromises } from '@vue/test-utils';
import HelloWorld from './HelloWorld.vue';
import { mockGet } from 'vi-fetch';
import 'vi-fetch/setup';

mockGet('api/welcome-message').willResolve('Welcome message from vitest');
mockGet('api/players').willResolve(['Mario', 'Luigi']);


test('the players have been rendered', async () => {
  const wrapper = mount(HelloWorld);
             
  await flushPromises();

  const lastPlayer = await wrapper.findAll('.player');
  expect(lastPlayer).toHaveLength(2);
});

demo