unit-testing - 如何在 vitest、vue/test-utils vue3 中对 vueuse/head 进行单元测试

标签 unit-testing vuejs3 vue-test-utils vitest

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

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 实例中加载的内容,我发现:

所以我将测试更改为:

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/

相关文章:

java - 单元测试 WorkManager 时周期性工作未达到运行状态

vue.js - 未捕获( promise )TypeError : Cannot read properties of undefined (reading 'completed' ) in Vue 3

javascript - 应用程序未初始化

vue.js - 如何检查 mixin 是否传递给了组件?

vue.js - "[vuex] state field foo was overridden by a module with the same name at foobar"与 deepmerge 辅助函数开 Jest

.net - 使用 TransactionScope 不会重新植入标识列

javascript - 使用 Resharper 测试运行程序时如何在我的 qunit 测试中设置断点

运行单元测试时 PHP 启动 : Unable to load dynamic library,

javascript - 将 D3 代码转换为 Vue3 - 单元格不添加到行而是添加到 HTML

vue.js - 如何使用 vue-test-utils 模拟生命周期钩子(Hook)