Sub topic 2
Setting up Jest or Vitest, jsdom, and jest-dom
This chapter assumes you know React function components and hooks, basic JavaScript with async/await, and the test, expect, and describe functions from Jest or Vitest. By the end you will have a project that can render a component and use jest-dom matchers.
What each piece does
A React Testing Library setup has four parts. Each solves a separate problem.
| Piece | Role |
|---|---|
| Test runner (Jest or Vitest) | Finds test files, runs them, and reports results. |
| jsdom | A JavaScript implementation of the browser DOM that runs inside Node.js. |
| `@testing-library/react` | Provides `render`, `screen`, and `renderHook`. |
| `@testing-library/jest-dom` | Adds DOM matchers such as `toBeInTheDocument` and `toBeDisabled`. |
Node.js has no document or window. The test environment option tells the runner to load jsdom, so React can create and update elements during a test.
Install the packages
For Jest, install the runner, the jsdom environment (it is a separate package since Jest 28), and the Testing Library packages. You also need Babel to transform JSX.
npm install --save-dev jest jest-environment-jsdom \
@testing-library/react @testing-library/dom \
@testing-library/jest-dom @testing-library/user-event \
babel-jest @babel/preset-env @babel/preset-reactFor Vitest, install Vitest and jsdom instead. Vitest handles JSX through Vite, so you need no Babel packages.
npm install --save-dev vitest jsdom \
@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 install it explicitly.
Configure the runner
Jest
Create jest.config.js. The setupFilesAfterEach name you may see in older notes is wrong. The correct option is setupFilesAfterEnv.
// jest.config.js
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
};Create babel.config.js so Jest can read JSX:
// babel.config.js
module.exports = {
presets: [
['@babel/preset-env', { targets: { node: 'current' } }],
['@babel/preset-react', { runtime: 'automatic' }],
],
};Vitest
Add a test block to vite.config.js. The globals option makes test, expect, and vi available without imports, which matches how Jest works.
// vite.config.js
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom',
globals: true,
setupFiles: ['./vitest.setup.js'],
},
});Register jest-dom in a setup file
Importing jest-dom once in a setup file registers its matchers for every test. Without this, toBeInTheDocument throws "is not a function".
// jest.setup.js (referenced from setupFilesAfterEnv in the Jest config)
import '@testing-library/jest-dom';
// Vitest equivalent in vitest.setup.js:
// import '@testing-library/jest-dom/vitest';If you use Vitest without globals: true, Testing Library cannot register its automatic cleanup. Rendered components then stay in the DOM between tests. In that case, call cleanup from afterEach yourself.
Verify the setup
Write a small component and a test. If both pass, the runner, jsdom, and jest-dom all work.
// Hello.jsx
export function Hello({ name }) {
return <h1>Hello, {name}</h1>;
}
// Hello.test.jsx
import { render, screen } from '@testing-library/react';
import { Hello } from './Hello';
test('renders a greeting', () => {
render(<Hello name="Ada" />);
expect(screen.getByRole('heading', { name: 'Hello, Ada' })).toBeInTheDocument();
});Add "test": "jest" (or "test": "vitest") to the scripts section of package.json, then run npm test.
Common setup errors
document is not defined: the test environment is stillnode. SettestEnvironment: 'jsdom'in Jest orenvironment: 'jsdom'in Vitest.toBeInTheDocument is not a function: the setup file is missing, has the wrong path, or is not listed in the config.Unexpected token '<'in Jest: Babel is not configured for JSX.jest is not definedin Vitest: useviinstead, for examplevi.fn().
Exercise
A test using expect(button).toBeDisabled() fails with "toBeDisabled is not a function", although @testing-library/jest-dom is installed. What is the most likely cause, and how do you fix it?
Show answer
The jest-dom matchers were never registered. Create a setup file that imports @testing-library/jest-dom (or @testing-library/jest-dom/vitest for Vitest) and list it in setupFilesAfterEnv (Jest) or setupFiles (Vitest).
Exercise
Why does a Jest project need testEnvironment: 'jsdom' to render React components?
Show answer
Jest runs in Node.js by default, which has no document or window. The jsdom environment provides a simulated browser DOM that React can render into.