Sub topic 2
Setting up Jest or Vitest, jsdom, and jest-dom
This chapter assumes you can write React function components with hooks, and that you know test, expect, and describe from Jest or Vitest. You should also be comfortable with async/await. By the end you will have a working test environment and a passing smoke test. Later chapters build on this setup without repeating it.
What the pieces do
A React Testing Library (RTL) test needs four things that work together.
- A test runner finds test files, runs them, and reports results. This chapter covers Jest and Vitest.
- A DOM implementation gives your components a
documentto render into. Tests run in Node.js, which has no browser DOM. jsdom is a JavaScript implementation of the DOM that runs inside Node. - A transform turns JSX into plain JavaScript. Jest usually uses Babel for this. Vitest uses Vite and esbuild.
- jest-dom matchers add DOM-aware assertions such as
toBeInTheDocument()andtoBeDisabled()toexpect.
If any one piece is missing, you get a different error. The troubleshooting section later in this chapter maps each error to its piece.
Installing the packages
RTL is split into several packages. Install them as development dependencies.
npm install --save-dev @testing-library/react @testing-library/dom \
@testing-library/jest-dom @testing-library/user-eventRecent versions of @testing-library/react list @testing-library/dom as a peer dependency, so you must install it yourself. Older versions bundled it. If npm warns about an unmet peer dependency, install the package it names. If you use TypeScript, also install @types/react and @types/react-dom.
Then add the runner-specific packages for the runner you chose.
Option A: Jest
Jest 28 and later do not bundle a browser-like environment. You install it separately.
npm install --save-dev jest jest-environment-jsdom babel-jest \
@babel/core @babel/preset-env @babel/preset-react identity-obj-proxyJest needs Babel to understand JSX, so add a Babel config.
// babel.config.js
module.exports = {
presets: [
['@babel/preset-env', { targets: { node: 'current' } }],
['@babel/preset-react', { runtime: 'automatic' }],
],
};The automatic runtime means you do not need import React from 'react' in every file. Now create the Jest config.
// jest.config.js
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
moduleNameMapper: {
'\\.(css|scss|sass)$': 'identity-obj-proxy',
},
};Each option has a job:
testEnvironment: 'jsdom'makeswindowanddocumentavailable in every test file.setupFilesAfterEnvlists files that run once per test file, after the test framework is installed. That timing matters because the setup file needsexpectto exist.moduleNameMapperreplaces stylesheet imports with a stub. Without it, Jest tries to parse CSS as JavaScript and fails.
Create the setup file.
// jest.setup.js
import '@testing-library/jest-dom';Importing the package once registers its matchers on the global expect for every test file.
Add a script to package.json.
{
"scripts": {
"test": "jest",
"test:watch": "jest --watch"
}
}Option B: Vitest
Vitest reuses your Vite configuration, so JSX and CSS imports work without extra transforms.
npm install --save-dev vitest jsdom @vitejs/plugin-reactCreate or extend the config. If you already have a vite.config.js, put the test block in it.
// vitest.config.js
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
setupFiles: ['./vitest.setup.js'],
globals: true,
},
});The setup file uses a Vitest-specific entry point of jest-dom, which extends Vitest's own expect.
// vitest.setup.js
import '@testing-library/jest-dom/vitest';The globals: true option makes test, expect, describe, and afterEach available without importing them, as in Jest. This matters for more than convenience, as the next section explains.
{
"scripts": {
"test": "vitest",
"test:run": "vitest run"
}
}vitest starts in watch mode during local development. vitest run runs once and exits, which is what you want in continuous integration.
Automatic cleanup and the globals setting
Every render call appends a container to document.body. If those containers piled up, one test could find elements left over from an earlier test. RTL prevents this by calling cleanup after each test, which unmounts the rendered trees and removes the containers.
RTL registers that hook by calling a global afterEach. Jest provides that global by default. Vitest provides it only when globals: true. If you prefer globals: false, register cleanup yourself.
// vitest.setup.js (for globals: false)
import { afterEach } from 'vitest';
import { cleanup } from '@testing-library/react';
import '@testing-library/jest-dom/vitest';
afterEach(() => {
cleanup();
});Symptoms of missing cleanup are tests that pass alone but fail together, and errors such as "Found multiple elements" for something you rendered once.
Comparing the two setups
| Concern | Jest | Vitest |
|---|---|---|
| DOM environment | `testEnvironment: 'jsdom'` plus `jest-environment-jsdom` | `test.environment: 'jsdom'` plus `jsdom` |
| JSX transform | Babel (`@babel/preset-react`) | Vite plugin (`@vitejs/plugin-react`) |
| jest-dom import | `@testing-library/jest-dom` | `@testing-library/jest-dom/vitest` |
| Setup file option | `setupFilesAfterEnv` | `setupFiles` |
| Mock function | `jest.fn()` | `vi.fn()` |
| Automatic cleanup | Works by default | Needs `globals: true` or a manual `cleanup` |
| CSS imports | Needs `moduleNameMapper` | Handled by Vite |
Choose Vitest if the project already uses Vite, because it shares one config and starts faster. Choose Jest if the project already has a Jest setup, such as in Create React App or a large existing suite. The RTL code you write is the same under both runners. Only the mock helpers differ.
Setting the environment for a single file
Sometimes only some test files need a DOM. Pure utility tests run faster in Node. You can set the default environment to node and opt in per file with a comment at the top.
/**
* @jest-environment jsdom
*/In Vitest, the equivalent comment is // @vitest-environment jsdom. Most projects set jsdom globally. The per-file form is useful when a few files need a different environment.
TypeScript notes
With TypeScript, the editor must know that expect has the jest-dom matchers. The setup file import usually handles this if the setup file is included by tsconfig.json. For Vitest, the import must be @testing-library/jest-dom/vitest, and vitest.setup.ts must be in the include list. If the editor reports that toBeInTheDocument does not exist on type Assertion, the setup file is not part of the compilation.
A smoke test
Before writing real tests, verify the whole chain with a small component and one test. This test uses jest.fn nowhere, so it runs under both runners. With Vitest and globals: false, import test and expect from vitest.
// Greeting.jsx
export function Greeting({ name }) {
return <h1>Hello, {name}</h1>;
}
// Greeting.test.jsx
import { render, screen } from '@testing-library/react';
import { Greeting } from './Greeting';
test('renders the greeting', () => {
render(<Greeting name="Ada" />);
expect(screen.getByRole('heading', { name: 'Hello, Ada' })).toBeInTheDocument();
});Run npm test. A passing result confirms that JSX is transformed, document exists, RTL can render, and the jest-dom matcher is registered. Each of those is a separate thing that could fail.
Troubleshooting by symptom
Match the error message to the missing piece.
| Error message | Missing piece | Fix |
|---|---|---|
| `ReferenceError: document is not defined` | DOM environment | Set the environment to `jsdom` in config or per file |
| `Test environment jest-environment-jsdom cannot be found` | Jest's jsdom package | Install `jest-environment-jsdom` |
| `SyntaxError: Unexpected token '<'` | JSX transform | Add the Babel preset (Jest) or the React plugin (Vitest) |
| `expect(...).toBeInTheDocument is not a function` | jest-dom registration | Add the import to the setup file and check the setup option name |
| `Invalid Chai property: toBeInTheDocument` | jest-dom registration in Vitest | Import `@testing-library/jest-dom/vitest`, not the default entry |
| `Found multiple elements` across tests | Cleanup | Enable `globals: true` or call `cleanup` in `afterEach` |
| `Cannot find module './styles.css'` | CSS stub | Add `moduleNameMapper` (Jest) |
Keeping the setup file small
The setup file runs before every test file, so keep it light. It is the right place for jest-dom, for cleanup in Vitest, and for global mocks that every test needs, such as window.matchMedia, which jsdom does not implement. Put anything that only some tests need in those tests or in a helper they import. Later chapters add a custom render helper for providers, and that belongs in a separate test-utils file rather than the setup file.
Exercise
A Vitest project has environment: 'jsdom' and a setup file containing import '@testing-library/jest-dom'. Tests run, but every toBeInTheDocument() call fails with "Invalid Chai property". Separately, with globals: false, tests that each render the same component start failing with "Found multiple elements". What two changes fix both problems?
Show answer
Change the setup import to @testing-library/jest-dom/vitest, which registers the matchers on Vitest's own expect. Then fix cleanup, either by setting globals: true in the Vitest config or by importing afterEach from vitest and cleanup from @testing-library/react in the setup file and calling afterEach(() => { cleanup(); }). RTL's automatic cleanup needs a global afterEach, which Vitest only provides when globals is true.
Exercise
Your Jest project throws ReferenceError: document is not defined in one component test, yet other test files pass. Name two ways to fix the failing file without changing how the other files run.
Show answer
Add a docblock comment at the top of the failing file: /** @jest-environment jsdom */. The other option is to set testEnvironment: 'jsdom' in the Jest config, which also covers the failing file, so a file that was somehow running in Node would then get a DOM. The per-file comment is the one that leaves other files untouched. Also confirm jest-environment-jsdom is installed.