Wil*_*llD 4 async-await vue.js vuejs3 vite vitest
我正在使用 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);
});
Run Code Online (Sandbox Code Playgroud)
我的组件脚本:
<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>
Run Code Online (Sandbox Code Playgroud)
.player <li>测试失败是因为,我认为,在测试查找引用之外的所有元素(使用 v-for 呈现)之前,在 onMounted 中运行的代码没有时间完成players。在测试失败之前,我如何要求 vitest 等待每个提取的响应。
谢谢。
ton*_*y19 20
获取将Promises在下一个宏 tick中解析,可以像这样等待:
test(\'...\', async() => {\n \xe2\x8b\xae\n await new Promise(r => setTimeout(r));\n})\nRun Code Online (Sandbox Code Playgroud)\n或者您可以使用Vue Test Utils 实用程序来执行此操作:
\nimport { flushPromises } from \'@vue/test-utils\';\n\ntest(\'...\', async() => {\n \xe2\x8b\xae\n await flushPromises();\n})\n\nRun Code Online (Sandbox Code Playgroud)\n在运行任何断言之前添加该行:
\n \nimport { mount, flushPromises } from \'@vue/test-utils\';\nimport HelloWorld from \'./HelloWorld.vue\';\nimport { mockGet } from \'vi-fetch\';\nimport \'vi-fetch/setup\';\n\nmockGet(\'api/welcome-message\').willResolve(\'Welcome message from vitest\');\nmockGet(\'api/players\').willResolve([\'Mario\', \'Luigi\']);\n\n\ntest(\'the players have been rendered\', async () => {\n const wrapper = mount(HelloWorld);\n \n await flushPromises();\n\n const lastPlayer = await wrapper.findAll(\'.player\');\n expect(lastPlayer).toHaveLength(2);\n});\nRun Code Online (Sandbox Code Playgroud)\n\n
| 归档时间: |
|
| 查看次数: |
14596 次 |
| 最近记录: |