首页 > 解决方案 > 如何使用 Jest 为 Yup.isValid 函数编写测试用例?

问题描述

我正在尝试添加一个单元测试来验证该Yup.isValid功能,但运行测试用例后显示错误为:Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL。即使我正在更改茉莉花的最小超时时间,也会显示相同的错误。我验证 Yup 模式的功能是:

export const validateSchema= (
  validationSchema,
  data
) => {
  return new Promise(async (resolve, reject) => {
    await validationSchema
      isValid(data)
      .then(isFormValid => {
        //passing response to method
      })
      .catch(error => reject(error));
  });
};

我的测试用例是:

test("validate Schema",async () => {
    let catchFn = jest.fn();
    let data= someSampleData;
    //data is valid as per the schema
   await validationSchema(
        validationSchema,
        data
      )
      .then(res => {
       //My expected condition
      })
      .catch(catchFn);
  });

上面的测试用例不会到我可以放置我的条件的地方。正如我提到的,同样的错误即将到来。我该如何解决这个问题?

标签: reactjsjestjsyup

解决方案


For large schemas it might be nice to use yup's validateAt api to pass in a path to validate for, so fixture data can be more concise.

Jest specs could look something like:

await expect(schema.validateAt(path, fixture)).rejects.toBeTruthy()
  it("requires person's name", async () => {
    await expect(schema.validateAt('person.name', {})).rejects.toBeFalsy()
    await expect(schema.validateAt('person.name', {person: {name: "something"}})).resolves.toBeTruthy()

  }

Unit testing yup is interesting, in that a lot of it is configuration, testing that libraries work the way they say they do can be extraneous. However, this does seem to helpful for testing more complex custom schema validation behaviors.


推荐阅读