Using Jest with React
Last updated on • Disponible en Français
Setting up Jest + React Testing Library in an Interview environment
In Interview React environments, we use Vite as the bundler and dev server for your React project. We chose Vite for its simple setup, out-of-the-box TypeScript support, and hot module reloading. Unfortunately, the integration between Vite and Jest is still a work in progress.
To use Jest in your React project, we suggest using Babel to transpile your code. Our recommended approach is largely borrowed from this Egghead.io course. In this example, we will also be installing Testing Library for React.
NPM Dependencies
First, you will need to install several dev dependencies:
# Babel Dependencies
npm install -D @babel/preset-env @babel/preset-react @babel/preset-typescript
# Testing-library Dependencies
npm install -D @testing-library/react @testing-library/jest-dom @testing-library/user-event
# Jest Dependencies
npm install -D jest jest-environment-jsdom
Code language: PHP (php)
Babel Configuration
Add a Babel config file in the root of the project called babel.config.js
.
module.exports = {
presets: [
'@babel/preset-env',
['@babel/preset-react', {runtime: 'automatic'}],
],
};
Code language: JavaScript (javascript)
Jest Configuration
Lastly, add a Jest config file and setup file in the root of the project called jest.config.js
and jest.setup.js
, respectively.
// jest.config.js
module.exports = {
clearMocks: true,
testEnvironment: "jsdom",
setupFilesAfterEnv: [
"<rootDir>/jest.setup.ts"
],
moduleNameMapper: {
"\\.(css|less)$": "identity-obj-proxy"
}
}
// jest.setup.js
import "@testing-library/jest-dom";
Code language: JavaScript (javascript)
At this point, you can add npm to your scripts to run Jest.
// In package.json
"scripts": {
"test": "jest",
"test:watch": "jest --watchAll"
}
Code language: JavaScript (javascript)
Now, you can run npm run test
or npm run test:watch
in the interactive shell to run the unit tests in your React project.
You can test this out in the sandbox below: