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

使用Vitest与Vue Test Utils时自定义组件未被替换为实现的问题

Vue Test Utils测试中自定义组件未正确渲染的问题解决

问题分析

你测试里的VInput组件没被替换成Input的实现,渲染结果还是<vinput>标签,核心问题出在组件注册的对象错了:

你在global.components里注册的是mount(Input, ...)返回的组件实例(Wrapper对象),但这里需要传入的是组件的原始定义(也就是你导入的Input),挂载后的实例是用来操作已渲染组件的工具对象,不能用来注册组件。

修正后的测试代码

import { describe, expect, test } from 'vitest';
import { mount } from '@vue/test-utils';
import VInputPhone from './InputPhone.vue';
import Input from '../Input.vue';

describe('InputPhone.vue', () => {
  test('Should render input with type tel', () => {
    const vModel: string = 'Input Value';

    const wrapper = mount(VInputPhone, {
      global: {
        // 直接传入组件定义,而非挂载后的实例
        components: { VInput: Input }
      },
      props: {
        modelValue: vModel
      }
    });

    console.log(wrapper.html());

    expect(wrapper.find('input').attributes().type).toBe('tel');
    expect(wrapper.find('input').attributes().type).not.toBe('text');
  });
});

关键修正点

  1. 删掉了多余的const VInput = mount(Input, ...)代码,这部分完全没必要,反而导致了错误的组件注册。
  2. 注册全局组件时直接用导入的Input组件,Vue Test Utils会在挂载VInputPhone时自动解析并渲染VInput对应的实际组件内容。
  3. 确保你的InputPhone.vue中给VInput传递了type="tel"的props,这样最终渲染的input才会是tel类型,断言才能通过。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 13:52:18