Skip to content

Commit

Permalink
Add unit test for validationEvent in resolver
Browse files Browse the repository at this point in the history
  • Loading branch information
slaymance committed Jun 2, 2024
1 parent 758ae10 commit f25ba2c
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 3 deletions.
6 changes: 3 additions & 3 deletions src/__tests__/useForm.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
} from '@testing-library/react';
import { act, renderHook } from '@testing-library/react-hooks';

import { VALIDATION_MODE } from '../constants';
import { EVENTS, VALIDATION_MODE } from '../constants';
import {
Control,
FieldErrors,
Expand Down Expand Up @@ -1139,7 +1139,7 @@ describe('useForm', () => {
{
test: 'test',
},
expect.objectContaining({ validationEvent: 'change' }),
expect.objectContaining({ validationEvent: EVENTS.CHANGE }),
{
criteriaMode: undefined,
fields: {
Expand All @@ -1164,7 +1164,7 @@ describe('useForm', () => {
{
test: 'test',
},
expect.objectContaining({ validationEvent: 'submit' }),
expect.objectContaining({ validationEvent: EVENTS.SUBMIT }),
{
criteriaMode: undefined,
fields: {
Expand Down
49 changes: 49 additions & 0 deletions src/__tests__/useForm/resolver.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from 'react';
import { act, fireEvent, render, screen } from '@testing-library/react';

import { EVENTS } from '../../constants';
import { useForm } from '../../useForm';
import noop from '../../utils/noop';
import sleep from '../../utils/sleep';
Expand Down Expand Up @@ -205,4 +206,52 @@ describe('resolver', () => {

expect(errorsObject).toEqual({});
});

it('should be called with the event that triggered validation', () => {
type FormValues = {
test: string;
};

const resolverSpy = jest.fn(() => ({ errors: {}, values: {} }));

const App = () => {
const { handleSubmit, register } = useForm<FormValues>({
mode: 'all',
resolver: resolverSpy,
});

return (
<form onSubmit={handleSubmit(() => null)}>
<input {...register('test')} />
<input type="submit" />
</form>
);
};

render(<App />);

const input = screen.getByRole('textbox');
const submit = screen.getByRole('button');

fireEvent.change(input, { target: { value: 'test' } });
expect(resolverSpy).toHaveBeenLastCalledWith(
expect.anything(),
expect.objectContaining({ validationEvent: EVENTS.CHANGE }),
expect.anything(),
);

fireEvent.blur(input);
expect(resolverSpy).toHaveBeenLastCalledWith(
expect.anything(),
expect.objectContaining({ validationEvent: EVENTS.BLUR }),
expect.anything(),
);

fireEvent.click(submit);
expect(resolverSpy).toHaveBeenLastCalledWith(
expect.anything(),
expect.objectContaining({ validationEvent: EVENTS.SUBMIT }),
expect.anything(),
);
});
});

0 comments on commit f25ba2c

Please sign in to comment.