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

求助:VTU无法读取mount()传入的props且shallowMount报错

问题解决:Vue Test Utils 无法读取props + shallowMount报错

问题1:props无法读取导致测试失败

你的组件代码中错误导入了defineProps——在Vue 3的<script setup>语法里,defineProps是编译器宏,不需要手动从vue包导入。多余的导入会干扰props的正常注入,导致模板无法读取传入的length值。

修复组件代码:

<template>
  <div class="otp-container" ref="otpContainer">
    <input
      data-test="otp-input"
      v-for="(digit, index) in length"
      :key="index"
      type="text"
      maxlength="1"
    />
  </div>
</template>

<script setup>
import { ref } from "vue";

// 移除defineProps的导入,直接使用编译器宏
const props = defineProps({
  length: {
    type: Number,
    required: true,
  },
});
</script>

修改后重新运行测试,props即可被组件正确读取,测试会正常通过。

问题2:"shallowMount is not a function"错误

Vue Test Utils v3(适配Vue 3)已经移除了shallowMount函数,改用mount函数的shallow选项实现浅渲染。

修复测试代码:

import { mount } from "@vue/test-utils";
import Otp from "../../src/components/Otp.vue";

describe("Otp.vue", () => {
  it("should render n otp inputs", () => {
    const wrapper = mount(Otp, {
      props: {
        length: 5,
      },
      shallow: true // 用此选项替代shallowMount
    });

    const otpInputs = wrapper.findAll('[data-test="otp-input"]');
    expect(otpInputs.length).toBe(5);
  });
});

额外验证(可选)

如果测试仍有异常,可在测试中添加日志确认props是否传递成功:

console.log("组件当前props:", wrapper.props());

运行后控制台应输出组件当前props: { length: 5 },以此确认props已正确传入。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 03:02:04