-
Hi! This library is very nice to me. I want to test behavior submitting. Form Component import { zodResolver } from '@hookform/resolvers/zod';
import { type FC } from 'react';
import { useForm, type SubmitHandler } from 'react-hook-form';
import { z } from 'zod';
const schema = z.object({
name: z.string(),
});
type Schema = z.infer<typeof schema>;
type Props = {
onValid: SubmitHandler<Schema>;
};
export const Form: FC<Props> = ({ onValid }) => {
const {
register,
handleSubmit,
formState: { isSubmitting },
} = useForm<Schema>({
mode: 'onChange',
defaultValues: { name: 'Ben' },
resolver: zodResolver(schema),
});
return (
<form onSubmit={handleSubmit(onValid)}>
<label>
<span>Name</span>
<input {...register('name')} />
</label>
<button disabled={isSubmitting}>submit</button>
</form>
);
}; Test import { render, screen, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import { Form } from './Form';
test('Submit button is disabled when submitting', async () => {
const user = userEvent.setup();
const onValid = () => {
expect(screen.getByRole('button', { name: /submit/ })).toBeDisabled();
};
render(<Form onValid={onValid} />);
await act(async () => {
await user.click(screen.getByRole('button', { name: /submit/ }));
});
}); This test is failed and accept the following: ● Submit button is disabled when submitting
expect(element).toBeDisabled()
Received element is not disabled:
<button /> I hope this hints at solving the problem. My version |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
It is solved! test('should be disabled when submitting, but should not be disabled when submitted', async () => {
const user = userEvent.setup();
let resolve: (v: unknown) => void;
const mockOnSubmit = jest.fn().mockReturnValue(
new Promise((_resolve) => {
resolve = _resolve;
})
);
render(
<Form
title="フォーム"
onSubmit={mockOnSubmit}
defaultValues={defaultValuesPassingValidations}
/>
);
await act(async () => {
await user.click(screen.getByRole('button', { name: /submit/ }))
});
expect(screen.getByRole('button', { name: /submit/ })).toBeDisabled();
await act(async () => {
resolve(jest.fn)
});
expect(screen.getByRole('button', { name: /submit/ })).not.toBeDisabled();
});
}); This key is in secrets of the act(...) api |
Beta Was this translation helpful? Give feedback.
-
Interesting, thanks for your resolve, it work for me |
Beta Was this translation helpful? Give feedback.
It is solved!