我有这个简单的单元测试:
import { describe, it, expect } from 'vitest';
import { mount } from '@vue/test-utils';
import Login from './Login.vue';
describe('Login.spec.js', () => {
it('mounts correctly', () => {
const wrapper = mount(Login, {});
expect(wrapper.isVisible()).toBe(true);
});
});
但是我的 Login.vue 组件有:
<script setup>
import { useHead } from '@vueuse/head';
...
useHead({
title: 'Login',
});
</script>
单元测试抛出错误:
[Vue warn]: injection "usehead" not found.
at <Login ref="VTU_COMPONENT" >
at <VTUROOT>
[Vue warn]: Unhandled error during execution of setup function
at <Login ref="VTU_COMPONENT" >
at <VTUROOT>
和
Error: You may forget to apply app.use(head)
❯ injectHead node_modules/@vueuse/head/dist/index.js:118:11
116| const head = (0, import_vue.inject)(PROVIDE_KEY);
117| if (!head) {
118| throw new Error(`You may forget to apply app.use(head)`);
| ^
119| }
120| return head;
如何克服这个错误?
编辑:我想我必须创建一个本地 vue 实例或安装了我的应用程序插件的东西,但我不知道如何去做。
最佳答案
我阅读了一些关于 Vue 实例中加载的内容,我发现:
- 在 vue test utils v1 中,您可以
createLocalVue
并将其作为安装选项传递。 - 在 vue test utils v2 中,您必须指定
插件
(此处描述:https://test-utils.vuejs.org/migration/#no-more-createlocalvue)。
所以我将测试更改为:
import { describe, it, expect, vi } from 'vitest';
import { mount } from '@vue/test-utils';
import { createHead } from '@vueuse/head';
import { createPinia } from 'pinia';
import PrimeVue from 'primevue/config';
import router from '@/router';
import Login from './Login.vue';
const head = createHead();
const pinia = createPinia();
describe('Login.spec.js', () => {
const wrapper = mount(Login, {
global: {
plugins: [head, pinia, PrimeVue, router],
},
});
it('mounts correctly', () => {
expect(wrapper.isVisible()).toBe(true);
});
});
现在可以使用了。
关于unit-testing - 如何在 vitest、vue/test-utils vue3 中对 vueuse/head 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72757318/