How to test a React App, with Jest and react-testing-library

Prerequisites: An existing React app.

You can find the full source code @ github: https://github.com/alexadam/project-templates/tree/master/projects/react-app-tests

Setup

Install Jest and react-testing-library

yarn add --dev jest @types/jest ts-jest @testing-library/react @testing-library/jest-dom

In the project's root folder, create a file named jest.config.js and add:

react-app/jest.config.js
module.exports = { roots: ["./src"], transform: { "^.+\\.tsx?$": "ts-jest" }, testEnvironment: 'jest-environment-jsdom', setupFilesAfterEnv: [ "@testing-library/jest-dom/extend-expect" ], testRegex: "^.+\\.(test|spec)\\.tsx?$", moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"] };

Update package.json by adding a new script entry:

react-app/package.json
"scripts": { ... "test": "jest", ...

Create a Test

We'll test the basic React app created from scratch here: https://alexadam.dev/blog/create-react-project.html

To test the Numbers component, create a file named numbers.test.tsx, in the src folder:

react-app/src/numbers.test.tsx
import React, { Props } from "react"; import { fireEvent, render, screen } from "@testing-library/react"; import Numbers from "./numbers"; describe("Test <Numbers />", () => { test("Should display 42", async () => { render(<Numbers initValue={42} />); const text = screen.getByText("Number is 42"); expect(text).toBeInTheDocument(); }); test("Should increment number", async () => { const { container } = render(<Numbers initValue={42} />) const incButton = screen.getByText('+') fireEvent( incButton, new MouseEvent('click', { bubbles: true, cancelable: true, }), ) const text = screen.getByText("Number is 43"); expect(text).toBeInTheDocument(); }); test("Should decrement number", async () => { const { container } = render(<Numbers initValue={42} />) const decButton = screen.getByText('-') fireEvent.click(decButton) const text = screen.getByText("Number is 41"); expect(text).toBeInTheDocument(); }); });

Run the tests:

yarn test

See the results:

$> yarn test
yarn run v1.22.17
$ jest
 PASS  src/numbers.test.tsx
  Test <Numbers />
    ✓ Should display 42 (29 ms)
    ✓ Should increment number (14 ms)
    ✓ Should decrement number (8 ms)

Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        2.893 s
Ran all test suites.
✨  Done in 3.88s.