DEV Community

Alan Johnson
Alan Johnson

Posted on • Edited on • Originally published at nalanj.dev

Ava and React Testing Library

The other day I needed to test a React hook with Ava, which lead me to try to use React Testing Library, and it took me a few minutes to figure out the best way to do so because the documentation to do so was spread over several pages.

I'm working with npm, so adjust commands as needed. First, set up some packages:

npm install react react-dom
npm install --save-dev ava @testing-library/react \
  global-jsdom jsdom
Enter fullscreen mode Exit fullscreen mode

Now we can write a basic test. This is a trivial example, but shows how everything comes together.

import "global-jsdom/register";

import React from "react";
import test from "ava";
import { render, screen, fireEvent, cleanup } from "@testing-library/react";

test.afterEach(cleanup);

function Button() {
  const [state, setState] = React.useState("Hello");

  return <button onClick={() => setState("World")}>{state}</button>;
}

test("setState", (t) => {
  render(<Button />);

  const button = screen.getByText("Hello");
  fireEvent.click(button);

  t.not(screen.getByText("World"), null);
});
Enter fullscreen mode Exit fullscreen mode

The crucial bits for getting this all working:

  • import "global-dom/register"; sets up jsdom globally in our tests.
  • test.afterEach(cleanup); makes sure that React Testing Library gets cleaned up after each test.

The rest is just normal React Testing Library usage.

Top comments (2)

Collapse
 
dorklord23 profile image
Tri R.A. Wibowo

Hello

I've been trying to integrate AVA and React to no avail. Could you share the repo of the sample?

Collapse
 
nalanj profile image
Alan Johnson

I’ve had some issues since React 18 came out that I never really found a solution to.