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

Setup

yarn add --dev jest @types/jest ts-jest @testing-library/react @testing-library/jest-dom
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"]
};
"scripts": {
...
"test": "jest",
...

Create a Test

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();
});

});
yarn test
$> 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.

--

--

--

https://alexadam.dev/

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Noteworthy Pros and Cons of the React Native Framework!

Introduction of JavaScript

Graphical representation of how execution context work behind the scene

Deploying a React Web Application that's created by create-react-app

Throttle expensive user-input processing with `useThrottledState`

Testing Medium

Container With Most Water

Angular vs React.js in Enterprise Level Application

Building a Desktop App in Go using Wails

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
alex adam

alex adam

https://alexadam.dev/

More from Medium

React Context Get Data From API

Creating a React Toolchain from Scratch. Part1.

Build a Custom Switch with React

Sync local and remote Zustand store in ReactJS