dry-scarletD
Refine3y ago
5 replies
dry-scarlet

Mock onError using Jest and React Testing Library

Hi everyone, need some help on how to mock the onError function. Basically I want to test the onError function if there's an error I want to test if the error displays? BTW I'm using react Toastify to display notification. any help is appreciated.

thanks,

const handleSubmit = (e: { preventDefault: () => void }) => {
    e.preventDefault();
    const payload = {......};

    mutate(
      {
        resource: 'project',
        values: payload,
        invalidates: ['all'],
      },
      {
        onSuccess: (data) => {
          if (data.data) {
            notify('Project created successfully');
          }
        },
        onError: (error) => {
          notifyError(error.response.data.errorMsg);
        },
      }
    );
  };


So far I managed to make the success notification

it('should clicked the button and display Project Objective created successfully', async () => {
    const setOpenModal = jest.fn();
    const { unmount } = renderWithToastify(
      <MyComponent setOpenModal={setOpenModal} />
    );
    const button = screen.getByRole('button');
    userEvent.click(button);
    expect(
      await screen.findByText('Project created successfully')
    ).toBeInTheDocument();
    unmount();
  });
Was this page helpful?