I am writing a test to ensure my form is submitting using react testing library and I am also using react hook form. My submit method is failing to be called within my test. I am greeting with the following error when this test runs:
● reset password should send
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
Can someone explain what I am doing incorrectly?
My component
const ResetPassword = () => {
const { handleSubmit } = useForm();
const onSubmit = (resetFormData: { email: string }) => {
const { email } = resetFormData;
// sends email using external API
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input
name="email"
type="text"
placeholder="Email Address"
/>
<button type="submit">
Send Email
</button>
</form>
);
};
export default ResetPassword;
My Test File
import userEvent from '@testing-library/user-event';
import { render, cleanup, screen, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
afterEach(cleanup);
it('reset password should send', async () => {
render(<ResetPassword />);
const handleSubmit = jest.fn();
const onSubmit = jest.fn();
const value = '[email protected]';
const input = screen.getByPlaceholderText(/Email Address/i);
await userEvent.type(input, value);
await act(async () => {
userEvent.click(screen.getByRole('button', { name: /Send Email/i }));
});
expect(onSubmit).toHaveBeenCalled();
});
onSubmitwith just the same name in your test will not do anything. For the interpreter this is a completely different function. You need to mock the actual function that gets called in you component. Also this is testing implementation details and is generally not recommended. A better way to test it would be to mock the actual fetch that happens on submit.