You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

测试自定义Vuetify组件时出现useGroup注入找不到的问题

问题解决:Vuetify v-expansion-panel 测试时注入错误

问题背景

基于Vue3的项目,使用Vuetify、vitest和vue-testing-library。自定义组件内部包含<v-expansion-panel>,业务中会被<v-expansion-panels>包裹,但单独测试时抛出错误:

Error: [Vuetify] Could not find useGroup injection with symbol vuetify:v-expansion-panel

尝试用包装组件将自定义组件包裹在<v-expansion-panels>内仍报错,但直接在包装组件里使用<v-expansion-panel>则正常。

解决方案

方案1:直接在测试模板中包裹父组件

调整测试代码,直接在渲染的模板里用<v-expansion-panels>包裹自定义组件,确保注入上下文正确传递:

import MyComponent from '@/components/MyComponent.vue';
import { describe, it } from 'vitest';
import { createVuetify } from 'vuetify';
import { render } from '@testing-library/vue';
import { screen } from '@testing-library/dom';

describe('<MyComponent />', () => {
  const vuetify = createVuetify();

  it('renders the component', async () => {
    render(`
      <v-expansion-panels>
        <MyComponent content="some text" />
      </v-expansion-panels>
    `, {
      global: {
        plugins: [vuetify],
        components: { MyComponent },
      },
    });

    expect(await screen.findByText('some text')).toBeInTheDocument();
  });
});

方案2:手动模拟注入上下文

如果不想依赖父组件,可以手动提供v-expansion-panel所需的注入内容,模拟<v-expansion-panels>的上下文:

import MyComponent from '@/components/MyComponent.vue';
import { describe, it } from 'vitest';
import { createVuetify } from 'vuetify';
import { render } from '@testing-library/vue';
import { screen } from '@testing-library/dom';
import { GROUP_ITEM_INJECTION_KEY } from 'vuetify/src/composables/group';

describe('<MyComponent />', () => {
  const vuetify = createVuetify();

  it('renders the component', async () => {
    render(MyComponent, {
      global: {
        plugins: [vuetify],
        provide: {
          [GROUP_ITEM_INJECTION_KEY as symbol]: {
            register: () => {},
            unregister: () => {},
            isActive: () => false,
            toggle: () => {},
          },
        },
      },
      props: { content: 'some text' },
    });

    expect(await screen.findByText('some text')).toBeInTheDocument();
  });
});

问题根源

<v-expansion-panel>依赖<v-expansion-panels>通过Vue的inject提供的分组上下文(useGroup),单独测试时没有这个父组件提供的上下文,因此抛出注入缺失的错误。两种方案分别通过提供真实父组件或模拟注入上下文解决了这个问题。

内容的提问来源于stack exchange,提问作者Andres Rosales

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 05:07:20