Jest and React Testing Library (RTL)
Jest and React Testing Library serve different but complementary roles in testing React components. We use both these libraries for writing unit tests.
1. Jest - Test Runner and Assertion Library
Jest is a Javascript testing Framework for Javascript that helps you write and run tests.
- A Test Runner: It finds and runs tests.
- Assertions: Allows writing expectations like
expect(something).toBe(somethingElse). - Mocking Capabilities: Helps in mocking functions, modules and APIs.
- Snapshot Testing: Captures component output to detect unexpected UI changes.
2. React Testing Library (RTL) - UI Testing Utility
React Testing Library is a set of helpful utilities to test React components in a way that mimics real user interactions. Instead of focusing on how the code is written, RTL encourages testing based on what users see and do, making your tests more reliable. RTL provides a virtual DOM for testing React components.
- DOM querying utilities: Helps find elements the way a user would. Example - getByText, getByRole, etc.
- Accessibility Testing: Promotes best practices by favoring queries based on accessibility.
- User interaction simulation: Provides fireEvent and userEvent to simulate clicks, typing, etc.
Why do we need both Jest and React Testing Library (RTL)?
- Jest runs the tests and provides assertions; But it doesn't render or interact with React components effectively.
- React Testing Library renders components and provides utilities to test them as users would interact with them.
So, Jest is essential for running tests, assertions, and mocking, while React Testing Library ensures tests focus on real user interactions.
Setting up Jest and React Testing Library in a Vite Typescript Project
1. Initialize the Vite Project with Typescript
Create a new Vite project with Typescript
npm create vite@latest my-vite-app --template react-tscd my-vite-appnpm install
2. Install Jest and Related Packages
Add Jest, Jest DOM, React Testing Library, and Babel for Jest transformation.
npm install --save-dev jest @testing-library/react @testing-library/jest-dom babel-jest @babel/preset-env @babel/preset-react @babel/preset-typescript
We are installing Jest, React Testing Library, and additional dependencies to ensure that Jest can correctly process and run our React code, especially JSX and TypeScript.
What are we installing and why do we need these packages?
- jest - The core testing framework
- @testing-library/react - The main library for testing React components by simulating user interactions.
- @testing-library/jest-dom - Provides custom matchers (like .toBeInTheDocument()) for better assertions on the DOM.
- babel-jest - Allows Jest to understand modern JavaScript features. Jest runs in Node.js, which doesn’t support JSX or TypeScript out of the box, so we need Babel to transform the code.
- @babel/preset-env - Converts modern JavaScript (ES6+) into a version that Jest can understand.
- @babel/preset-react - Transforms JSX into regular Javascript.
- @babel/preset-typescript - Enables Jest to work with TypeScript if we are using it.
3. Install Additional Jest Environment for JSDOM
Jest, by default, runs in a Node.js environment, which doesn't have a browser-like DOM. Previously, Jest included JSDOM (a JavaScript-based browser simulation), but now we need to install it separately.
npm install --save-dev jest-environment-jsdom
What are we doing here? We are installing
jest-environment-jsdomso Jest can simulate a browser-like environment for testing React components that interact with the DOM (like rendering elements, handling events, etc.).
4. Configure Babel to Automatically Import React
If you're using React 17+ you don't need to import React to create your components. While writing your tests however, you might need to import React. There are 2 ways to solve this. First is to explicitly import React in all your test files. The second option is to configure Babel to automatically import it for you.
This is how it can be done. Install the following plugin:
npm install --save-dev @babel/plugin-transform-react-jsx
5. Create Babel Configuration
Jest runs in Node.js, which doesn't support JSX or TypeScript by default. Babel helps convert our React code into standard JavaScript that Jest can execute.
In this step we are configuring Babel to transform our modern JavaScript (JSX, ES6+, and TypeScript) into a format that Jest can understand.
Create a babel.config.cjs file.
// babel.config.cjsmodule.exports = { presets: [ '@babel/preset-env', // Converts modern JavaScript to an older version that Jest understands '@babel/preset-react', // Transforms JSX into JavaScript '@babel/preset-typescript' // Allows Jest to process TypeScript files ], plugins: [ ['@babel/plugin-transform-react-jsx', { runtime: 'automatic' }] // Enables automatic JSX transformation (no need to import React in every file) ]};
6. Create Jest Configuration File
Jest needs some guidance to properly interpret our files (like JSX, CSS imports, and TypeScript) and set up the correct testing environment.
Here we are telling Jest how to run our tests by specifying the environment, file transformations, and additional setups.
Create a jest.config.cjs file.
// jest.config.cjsmodule.exports = { testEnvironment: 'jest-environment-jsdom', // Ensures Jest simulates a browser environment transform: { '^.+\\.tsx?$': 'babel-jest', // Tells Jest to use Babel for transforming TypeScript (.ts, .tsx) files }, moduleNameMapper: { '\\.(css|less|sass|scss)$': 'identity-obj-proxy', // Mocks CSS imports so Jest doesn't break on style imports }, setupFilesAfterEnv: ['@testing-library/jest-dom'], // Loads additional matchers like `.toBeInTheDocument()`};
7. Clear Jest Cache (Optional)
If you encounter issues clearing Jest's cache can help.
npx jest --clearCache
8. Add a Test Script to package.json
"scripts": { "test": "jest"}
If you want the tests to be run in the watch mode (where jest continuously monitors all your tests), then add a --watchAll flag to your script like this:
"scripts" : { "test": "jest --watchAll"}
In Jest, the default output shows which test files ran and their pass/fail status, but it doesn't list each test's name unless there's a failure or you enable verbose output.
To enable the verbose output we need to add the --verbose flag to the test script.
"scripts" : { "test": "jest --watchAll --verbose"}
9. Run your Tests
Finally run the tests with:
npm run test
Types of Tests
- Unit Test
- Tests a single function or component in isolation.
- Ensures that one small piece of code works correctly.
- Example: Checking if a button component renders with the correct label.
- Integration Test
- Tests how multiple components or functions work together.
- Ensures that different parts of the app interact correctly.
- Example: Testing if a form submits data and updates the UI properly.
- End to End Test
- Tests the entire application flow from start to finish.
- Simulates real user interactions in a browser.
- Example: Checking if a user can log in, add a product to the cart, and complete checkout.
Anatomy (Structure) of a Test
Every test begins with the test method (provided by Jest) which can accept 3 arguments.
test(name, fn, timeout)
- First argument is the test name used to identify a test.
- Second argument is a function that contains the expectations to test.
- Third argument (optional) specifies how long to wait before aborting a test. Default is 5 seconds.
Let's take a look at this simple test.
import {render, screen} from '@testing-library/react'import TestComponent from './TestComponent'test('renders the test component', () => { render(<TestComponent />) const headingElement = screen.getByText(/test component/i) expect(headingElement).toBeInTheDocument()})
- In the above example we begin by creating the Virtual DOM of the TestComponent by using the render method provided by RTL (React Testing Library).
- We also use screen from RTL which is an object that contains methods to query the Virtual DOM. We can get hold of the element from the virtual DOM against which we need to assert.
- We use the expect method (from Jest) along with toBeInTheDocument (matcher function) to carry out the assertion.
In testing, an assertion is a statement that verifies whether a certain condition is true within the test.
Notice that in the file above we are using the methods like test, and expect (provided by jest) without importing any of these methods. It is possible because Jest automatically makes these globally available in your test files.
