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:

1
2
3
npm install react react-dom
npm install --save-dev ava @testing-library/react \
  global-jsdom jsdom

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
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);
});

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.

Love it? Hate it? Have something to say? Let me know at comments@nalanj.dev.