Testing that function throws inside React component

Viewed 144

How would one test that a function inside a React component throws using React Testing Library? I would have expected the code below to work but it does not.

import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

function MyComponent() {
  function doStuff() {
    throw new Error("my-error");
  }

  return <p onClick={doStuff}>my-button</p>;
}

describe("<MyComponent/>", () => {
  it("throws", () => {
    render(<MyComponent />);
    const button = screen.getByText("my-button");
    expect(() => userEvent.click(button)).toThrowError(/my-error/);
  });
});
0 Answers
Related