React / 71
Set up Vitest (or Jest) with React Testing Library
Install a test runner, a fake browser (jsdom) and the Testing Library packages, then point them at each other with a few lines of config.
Who does what
the test runner: finds *.test.jsx files, runs them, reports pass/fail
a fake browser DOM (document, window, events) running in Node
@testing-library/react
render · screen
@testing-library/user-event
user.click · user.type
@testing-library/jest-dom
toBeInTheDocument()
| Package | Job |
|---|---|
vitest or jest | The runner: finds test files, runs them, reports results. Also gives you test, expect, mocks. |
jsdom | A fake browser DOM in Node (document, window, events). Tests don't open a real browser. |
@testing-library/react + @testing-library/dom | render a component, then find things with screen |
@testing-library/jest-dom | DOM checks like toBeInTheDocument(). Works with Vitest too, despite the name. |
@testing-library/user-event | Realistic clicks and typing |
The setup
Use Vitest if your app uses Vite (today's default). Use Jest if your project already does, or isn't on Vite. (Vitest 5 needs Vite 6.4+ and Node 22.12+.)
npm install -D vitest jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom @testing-library/user-eventnpm install -D jest jest-environment-jsdom babel-jest @babel/core @babel/preset-env @babel/preset-react @testing-library/react @testing-library/dom @testing-library/jest-dom @testing-library/user-eventVitest
Add a test block to the Vite config you already have:
/// <reference types="vitest/config" />
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
test: {
environment: "jsdom", // fake browser
globals: true, // test/expect without imports + auto cleanup
setupFiles: "./src/setupTests.js",
},
});import "@testing-library/jest-dom/vitest";{
"scripts": {
"test": "vitest",
"coverage": "vitest run --coverage"
}
}npm test starts in watch mode and re-runs the affected tests on every save; npx vitest run runs once (handy for CI).
Jest
Jest doesn't understand JSX or import on its own, so Babel translates your files first:
{
"presets": [
["@babel/preset-env", { "targets": { "node": "current" } }],
["@babel/preset-react", { "runtime": "automatic" }]
]
}{
"testEnvironment": "jsdom",
"setupFilesAfterEnv": ["<rootDir>/jest.setup.js"]
}import "@testing-library/jest-dom";Then add "test": "jest" and "test:watch": "jest --watch" to your scripts. (npm init jest@latest can also generate a config by asking you questions.)
Where tests live
Name test files *.test.jsx (or .test.js, .spec.jsx) and put them next to the code they test, or in a __tests__ folder. Both runners find them automatically. Add coverage/ to .gitignore: it's generated output.
Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
