使用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'); }); });
关键修正点
- 删掉了多余的
const VInput = mount(Input, ...)代码,这部分完全没必要,反而导致了错误的组件注册。 - 注册全局组件时直接用导入的
Input组件,Vue Test Utils会在挂载VInputPhone时自动解析并渲染VInput对应的实际组件内容。 - 确保你的
InputPhone.vue中给VInput传递了type="tel"的props,这样最终渲染的input才会是tel类型,断言才能通过。
内容的提问来源于stack exchange,提问作者Brum
相关产品推荐
相关产品推荐

