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

Android emulator setup for expo on mac

Build An Interactive Monkey Login Panel Using HTML, CSS, and Javascript.

Learn GatsbyJS by creating a tourism site -6

Leetcode 1446: Consecutive Characters

How To Use Nodemon To Restart Your Node.js Applications

Hand holding Pokeball

Leetcode 2138: Divide a String Into Groups of Size k

Top 5 Front-End JavaScript Frameworks & Libraries in 2019

Top 5 FrontEnd Javascript

How to update object with useState | How to add object or fields in array of objects in useState |…

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

Considerations for writing React Components — Part 01: Introduction

Moving components using react.

Using the native form element with React

Usage of CSS modules in React