我有一个简单的单元测试:
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实例或者什么东西,但是我不知道该怎么做。
发布于 2022-06-26 20:58:02
我在加载Vue实例时进行了一些阅读,发现在vue测试实用程序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);
});
});现在起作用了。
https://stackoverflow.com/questions/72757318
复制相似问题