6

我正在尝试添加一个单元测试来验证该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);
  });

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

4

3 回答 3

1

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.

于 2019-09-20T16:20:22.890 回答
1

validateSchema使用 Promise 构造反模式并显示它被视为反模式的原因之一new Promise是容易出现人为错误的不需要的构造。

使用asyncas Promiseexecutor 是导致反模式的错误。executor 忽略从函数 Promise返回的承诺。永远不会被调用,while是无操作的。返回被拒绝或待处理的承诺。如果从测试中返回待处理的 Promise,则会导致超时。asyncresolve.catch(error => reject(error))validateSchema

它应该是:

export const validateSchema= async (
  validationSchema,
  data
) => {
    await validationSchema;
    const isFormValid = isValid(data);
    await updateFormValidFlag(isFormValid, theFormName); // does it return a promise?
  });
};

await很少需要混合和原始的承诺。在测试中使用虚拟函数catch将导致抑制错误,这很少是可取的行为。

测试可以是:

test("validate Schema",async () => {
   let data= someSampleData;
   await validateSchema(...);
   //My expected condition
});
于 2019-01-14T12:45:52.467 回答
0

再举一个例子,我主要是检查真值

it( 'should handle validating object', async () => {
  const result = await schema.isValid(myObject)
  expect( result ).toEqual( true )
} )
于 2020-09-16T12:20:10.967 回答