Skip to main content

A Quick Guide to Jest and React Testing Library

Jest: A Snapshot

Jest is a JavaScript testing framework developed by Facebook.

It’s easy to use, fast, and comes with a rich API.

React Testing Library: The Companion

React Testing Library is a popular tool for rendering React components in tests. It complements Jest perfectly.

Setting Up

Install the necessary libraries with:

npm install --save-dev @testing-library/react @testing-library/jest-dom jest jest-environment-jsdom @babel/preset-env @babel/preset-react

Update package.json:

{
"scripts": {
"test": "jest"
},
"jest": {
"testEnvironment": "jsdom"
}
}

Create .babelrc:

{
"presets": [
"@babel/preset-env",
["@babel/preset-react", { "runtime": "automatic" }]
]
}

Testing with Jest

Consider a simple component that displays a message:

// Message.js

const Message = ({ text }) => <p>{text}</p>

export default Message;

We can test this with Jest and React Testing Library:

// Message.test.js

import React from 'react'
import { render, screen } from '@testing-library/react'
import Message from './Message'

test('renders message', () => {
const text = 'Hello, Jest!'
render(<Message text={text} />)
expect(screen.getByText(text)).toBeDefined()
})

Run the test with npm test. If everything is set up correctly, the test will pass.