1

I have a very simple form in which i try to test that once the submit button is hit the mock function is called, but to no success, It works when i test that the input was changed, but clicking the button doesn't submit the button here is the code

  const mockFunct = vi.fn((data: any) => {
    return Promise.resolve(data);
  });  

  it('Should submit the form ', async () => {
    const { getByPlaceholderText, getByText, getByTestId } = render(
      <Form submitHandler={mockFunct} />
    );
    const usernameInput = getByPlaceholderText('Username') as HTMLInputElement;
    const passwordInput = getByPlaceholderText('Password') as HTMLInputElement;

    const submitBtn = getByText('Submit') as HTMLButtonElement;
    const form = getByTestId('form') as HTMLFormElement;

    fireEvent.change(usernameInput, { target: { value: 'Sam12_#' } });
    fireEvent.change(passwordInput, { target: { value: 'pass' } });

    expect(usernameInput.value).toBe('Sam12_#');
    expect(passwordInput.value).toBe('pass');

    expect(form).toBeDefined();
    expect(submitBtn.textContent).toBe('Submit');

    fireEvent.submit(submitBtn);
    fireEvent.submit(screen.getByRole('button'));

    expect(mockFunct).toHaveBeenCalled();
  });

Here is the code for the component itself

export interface FormProps {
  submitHandler: (data: any) => void;
}

const schema = yup.object().shape({
  username: yup.string(),
  password: yup.string(),
});

export function Form({ submitHandler }: FormProps) {
  const { register, handleSubmit } = useForm({
    resolver: yupResolver(schema),
  });
  return (
    <div className={styles['container']}>
      <h1 className={styles['title']}>Welcome to Form!</h1>
      <form
        className={styles['form']}onSubmit={handleSubmit(submitHandler)}data-testid="form">
        <input
          {...register('username')}className={styles['box']}placeholder="Username"
        />
        <input {...register('password')}className={styles['box']}placeholder="Password"/>
        <button type="submit" className={styles['btn']}>Submit</button>
      </form>
    </div>
  );
}

The error i get is always "AssertionError: expected "spy" to be called at least once"

Thanks in Advance.

CinemaClub
  • 69
  • 6

0 Answers0