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

yup字符串验证对数字输入未生效,Jest单元测试失败求解决

Yup数据验证不符合预期的解决思路

问题原因

你的测试未通过是因为Yup v0.x版本的string()规则默认会进行隐式类型转换——它会自动把数字123转换成字符串"123",因此验证结果为true,和你的预期不符。

解决方法

通过启用严格模式关闭隐式类型转换,让Schema严格校验原始数据类型:

修改后的测试代码:

import { object, string } from 'yup';

test('validator', async () => {
  let schema = object({
    // 添加 .strict() 禁用类型转换
    name: string().strict(),
  });

  expect(await schema.isValid({ name: 123 })).toEqual(false);
});

补充说明

  • strict()方法会让Schema完全跳过类型转换逻辑,仅校验数据的原始类型是否匹配
  • 如果需要自定义类型不匹配时的错误提示,可以搭配typeError()使用:
    string().strict().typeError("name必须是字符串类型")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:00:24