使用Yup验证以检查数组长度->如果length === 1则错误

时间:2020-06-02 09:19:04

标签: javascript reactjs yup

我有以下对象:

{
    array: [1]
}

以及以下代码:

myArray: Yup.array().of(
    Yup.object().shape({
        name: Yup.string().max(255).required().label('Name')
    })
)

现在,我检查名称是否为必填项,我需要检查myArray是否具有length === 1才能返回错误。

1 个答案:

答案 0 :(得分:1)

如果您想测试office-addin-debugging start manifest.xml web Debugging is being started... App type: web Unable to start the dev server. Error: Platform not supported: Linux Debugging started. ,则可以使用mixed.test(options: object)

it('should do something...', () => {
    // insert here initialisation for variables eventLabel, eventCategory, eventAction, eventValue with appropriate values
    const gaSpy = spyOn((window as any), 'ga');
    service.emitEvent(eventLabel, eventCategory, eventAction, eventValue);
    expect(gaSpy).toHaveBeenCalledWith('send', 'event', {
      eventLabel,
      eventCategory,
      eventAction,
      eventValue,
    });
  });

演示:

Edit holy-http-e3y4e

还有array.min(limit: number | Ref, message?: string | function),如果您想测试length === 1

myArray: array()
  .of(
    object().shape({
      name: string()
        .max(255)
        .required()
        .label("Name")
    })
  )
  .test({
    message: 'The error message if length === 1',
    test: arr => arr.length !== 1,
  })

演示:

Edit happy-sea-dds1e