首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在vue/ test -utils vue3中对vueuse/head进行单元测试

如何在vue/ test -utils vue3中对vueuse/head进行单元测试
EN

Stack Overflow用户
提问于 2022-06-25 20:59:43
回答 1查看 536关注 0票数 0

我有一个简单的单元测试:

代码语言:javascript
运行
复制
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组件有:

代码语言:javascript
运行
复制
<script setup>
import { useHead } from '@vueuse/head';

...

useHead({
    title: 'Login',
});
</script>

单元测试正在抛出错误:

代码语言:javascript
运行
复制
[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>

代码语言:javascript
运行
复制
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实例或者什么东西,但是我不知道该怎么做。

EN

回答 1

Stack Overflow用户

发布于 2022-06-26 20:58:02

我在加载Vue实例时进行了一些阅读,发现在vue测试实用程序v1中,您可以将其作为一个挂载选项传递给createLocalVue。在vue test utils v2中,您必须指定插件(在这里描述:https://test-utils.vuejs.org/migration/#no-more-createlocalvue)。

所以我把我的测试改为:

代码语言:javascript
运行
复制
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);
    });
});

现在起作用了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72757318

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档