Introduction
React Testing Library(RTL) is a react component testing tool that is highly functional and useful for unit testing and QA. To learn more about the React Testing Library and its setup, check out Testing React App with Jest and React Testing Library Setup.
This article will explore the implementation of the React Testing Library with the Jest Testing framework in JavaScript with some examples. This article requires basic knowledge of the Jest framework. So if you are not familiar with Jest, check out our introductory articles Getting Started with Jest and Writing your first Unit Test with Jest.
React Test Example
There are two methods of implementing a React test using Jest and React Testing Library.
- You can use the Create React App(CRA) to create a react application. The React app you create with CRA will already include Jest and React Testing Library, so you can start testing immediately.
npx create-react-app test-example
- You can also implement the React Testing Library without CRA. In that case, you will need to install Jest and React Testing Library manually in your node project using NPM.
npm install --save-dev @testing-library/react jest
In this article, we will use the default template of CRA to create a new React application. The React app(test-example) that you will make using the command above will already include App.js and App.test.js inside the src folder with the following content.
Program
// src/App.js
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
Program
// src/App.test.js
import { render, screen } from "@testing-library/react";
import App from "./App";
test("renders learn react link", () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
The App.test.js file uses the render method from React Testing Library to render the App component from App.js virtually and append it to the document.body.
We access the rendered HTML through the screen object. The screen object also has DOM testing methods bound into it. That's why the above test code is using screen.getByText() to query the anchor <a> element by its textContent value.
The test finally asserts if the link element is available in the document object with Jest’s expect method.
You can run the test using the npm run test inside your app from the command line.
Output
You can also see the output of the render() call by using the screen.debug() method after it. That will render the whole document.body in your console log when you run the test.
Program
test("renders learn react link", () => {
render(<App />);
screen.debug();
...
});