Jest.js VTU未阅读传递给mount()函数的props对象

o4tp2gmn  于 6个月前  发布在  Jest
关注(0)|答案(1)|浏览(82)

当使用props对象挂载组件时,VTU不会从传递给mount()函数的选项对象中读取props,因此测试总是失败。

Otp.vue

<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, defineProps } from "vue";

const props = defineProps({
  length: {
    type: Number,
    required: true,
  },
});
</script>

字符串

Otp.spec.js

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,
      },
    });

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


我试着使用shallowMount,它甚至说shallowMount不是一个函数,我希望otp输入的长度是5(因为它通过 prop 传递)

avkwfej4

avkwfej41#

看起来<script setup>中只定义了props,但是模板使用了length,所以请尝试

v-for="(digit, index) in props.length"

字符串

import { toRef } from 'vue';

const length = toRef(() => props.length);

相关问题