简体   繁体   English

react-hook-form 的 formstate.errors 开玩笑测试中的奇怪行为

[英]react-hook-form's formstate.errors weird behavior in jest test

I would like to do validation onBlur.我想对 onBlur 进行验证。 But when I am testing it in jest, the error message will not show up in first onblur in first test clause.但是当我开玩笑地测试它时,错误消息不会出现在第一个测试子句的第一个 onblur 中。 However, it shows up in second onblur in second test clause.但是,它出现在第二个测试子句的第二个 onblur 中。

Here I show the DOM from first and second clause and we can see the error message shows up in 2nd clause after second onblur.这里我展示了第一个和第二个子句的 DOM,我们可以看到错误消息显示在第二个 onblur 之后的第二个子句中。

How to make the error message showing up in the first onblur in first test clause?如何使错误消息显示在第一个测试子句的第一个 onblur 中?

React File反应文件

import React from 'react';
import { useForm } from 'react-hook-form';
import { string, object } from 'yup';
import { yupResolver } from '@hookform/resolvers/yup';

interface TestingProps {
  fullname: string;
}

const TestingPage: React.FC = () => {
  const schema = object().shape({
    fullname: string().required('fullname is required!')
  });

  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm<TestingProps>({
    resolver: yupResolver(schema),
    mode: 'onBlur'
  });

  const submit = () => {};

  return (
    <div>
      <form onSubmit={handleSubmit(submit)}>
        <input className="testing" {...register('fullname')} />
      </form>
      {errors?.fullname && <p>{errors.fullname.message}</p>}
      <input type="submit" />
    </div>
  );
};
export default TestingPage;

Jest Test File笑话测试文件

import Enzyme, { mount } from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
import TestingPage from './TermsAndConditions';

Enzyme.configure({ adapter: new Adapter() });

describe('Testing page test', () => {
  let wrapper: any;

  test('first attempt to show error message onblur', () => {
    wrapper = mount(<TestingPage />);
    wrapper.find('.testing').simulate('focus');
    wrapper.find('.testing').simulate('blur');
    console.log(wrapper.debug());
  });

  test('second attempt to show error message onblur', () => {
    wrapper.find('.testing').simulate('blur');
    console.log(wrapper.debug());
  });
});

DOM 截图

You just need to await before test assertion, because react-hook-form validation and submit are async.您只需要在测试断言之前await ,因为 react-hook-form 验证和提交是异步的。 Use flush-promises eg使用刷新承诺,例如

function flushPromises() {
    return new Promise(resolve => setImmediate(resolve));
}

  test('first attempt to show error message onblur', async () => {
    wrapper = mount(<TestingPage />);
    wrapper.find('.testing').simulate('focus');
    wrapper.find('.testing').simulate('blur');
    await flushPromises();
    console.log(wrapper.debug());
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM