I would like to do validation onBlur. But when I am testing it in jest, the error message will not show up in first onblur in first test clause. However, it shows up in second onblur in second test clause.
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.
How to make the error message showing up in the first onblur in first test clause?
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());
});
});