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

VeeValidate4:测试useField自定义字段组件及消除控制台警告

测试VeeValidate4自定义输入组件的问题

我尝试测试基于VeeValidate4 useField 的自定义输入组件,未找到专门的测试指导,仅参考官方「Mocking Form and Field Contexts」文档编写了测试用例。测试功能正常,但控制台出现警告,想确认测试写法是否正确,以及如何消除这些警告。

自定义组件代码

<script setup>
import { useField } from 'vee-validate';
import { watch, toRef } from 'vue';

const props = defineProps({
  modelValue: {
    type: undefined,
    default: undefined,
  },

  type: {
    type: String,
    default: 'text',
  },

  label: {
    type: String,
    default: '',
  },

  name: {
    type: String,
    required: true,
  },
});

const emit = defineEmits(['update:modelValue']);

const { value, setValue, errorMessage } = useField(toRef(props, 'name'));

watch(
  () => value.value,
  (newValue) => {
    emit('update:modelValue', newValue);
  }
);

watch(
  () => props.modelValue,
  (newValue) => {
    setValue(newValue);
  }
);
</script>

<template>
  <div class="form-group">
    <label v-if="props.label" :for="props.label">{{ props.label }}</label>

    <input
      :id="props.label"
      v-model="value"
      :name="props.name"
      :type="props.type"
      class="form-input"
    />

    <span v-if="errorMessage" class="form-error" role="alert">{{ errorMessage }}</span>
  </div>
</template>

测试文件代码

import { render, screen, waitFor } from '@testing-library/vue';
import AppField from './AppField.vue';
import { FormContextKey, useForm } from 'vee-validate';
import userEvent from '@testing-library/user-event';

const rednerField = ({ label, type, ...rest } = {}) => {
  const options = { props: { name: 'inputName', label, type }, ...rest };

  render(AppField, options);
};

const user = userEvent.setup();

const MockedForm = useForm({
  validationSchema: {
    inputName(value) {
      if (value && value.trim()) {
        return true;
      }

      return 'This is required';
    },
  },
});

describe('showing error', () => {
  it('show error if field is invalid', async () => {
    rednerField({ label: 'labelName', global: { provide: { [FormContextKey]: MockedForm } } });
    const input = screen.getByLabelText('labelName');

    user.type(input, ' ');

    await waitFor(() => {
      expect(screen.getByRole('alert')).toHaveTextContent('This is required');
    });
  });
});

问题确认

测试能正常验证功能,但控制台会弹出警告。想明确两个问题:

  • 当前的测试写法是否符合VeeValidate4的测试规范?
  • 如何消除控制台的警告?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:45:31