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

如何使用Jest测试自定义Yup验证规则?

为自定义Yup验证方法编写Jest单元测试

自定义验证方法实现

以下是用于校验数组内每个对象from值小于to值的自定义Yup验证器:

function nextValueBigger(message = 'Some error') {
  return this.test('nextValueBigger', (value, { path }) => {
    const errors = value.map((item, index) => {
      if (item?.from < item?.to) { return null; } // 校验通过,无错误

      return new ValidationError(
        message,
        null,
        `${path}[${index}].to`,
      );
    }).filter(Boolean);

    if (errors.length === 0) { return true; }

    return new ValidationError(errors);
  });
}

测试代码修正与补充

你当前的测试代码存在字段名不匹配、语法错误以及断言逻辑错误的问题,下面是修正后的完整测试方案:

正确数据的测试用例

// 校验通过的测试数据
const validItems = [
  { from: 1, to: 2 },
  { from: 3, to: 4 },
  { from: 5, to: 6 },
];

// 修正字段名一致的Schema
const schema = Yup.object().shape({
  items: Yup.array().of(Yup.object().shape({
    from: Yup.number(),
    to: Yup.number(),
  }))
    .nextValueBigger(),
});

it('校验通过时无错误返回', async () => {
  // validateAt校验成功会返回对应字段的原始值,而非true
  const result = await schema.validateAt('items', { items: validItems });
  expect(result).toEqual(validItems);
});

错误数据的测试用例

为了覆盖完整场景,还需要测试校验失败的情况:

// 包含错误的测试数据(第二个对象from大于to)
const invalidItems = [
  { from: 1, to: 2 },
  { from: 5, to: 4 },
  { from: 6, to: 7 },
];

it('校验失败时抛出正确的ValidationError', async () => {
  // 验证是否抛出ValidationError
  await expect(schema.validateAt('items', { items: invalidItems }))
    .rejects.toThrow(Yup.ValidationError);
  
  // 进一步验证错误信息和错误路径
  try {
    await schema.validateAt('items', { items: invalidItems });
  } catch (error) {
    expect(error.errors[0]).toBe('Some error');
    expect(error.paths[0]).toBe('items[1].to');
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 16:20:47