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

在Vitest与Nuxt 3中测试组件Props时遇未定义读取错误求助

解决Nuxt3 + Vitest组件Props测试未定义错误
  • Prop命名不匹配:测试代码中传递的prop是intro_title,但组件内defineProps定义的是驼峰式的introTitle,两者名称不一致导致组件无法识别传入的属性。
  • 依赖Prop未传递:组件内的imageUrl计算属性依赖introImage,但测试时未传入该prop,会导致计算逻辑出错,同时可能影响其他prop的渲染。

修正后的测试代码

import Intro from '../components/Intro.vue';
import { mount } from '@vue/test-utils';
import { test, expect} from "vitest";

test('Intro 组件渲染传入的标题', () => {
    const wrapper = mount(Intro, {
        props: {
            introTitle: 'Hello',
            introImage: 'test-image.jpg' // 补充组件依赖的prop
        }
    });
    expect(wrapper.text()).toContain('Hello');
});

组件优化建议(可选)

给props设置默认值,避免未传入时出现undefined错误:

const props = defineProps({
  introImage: {
    type: String,
    default: 'default-image.jpg'
  },
  introTitle: {
    type: String,
    default: ''
  },
  introText: {
    type: String,
    default: ''
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 10:16:03