Introduction
Writing tests is crucial for maintaining a scalable React application. But if you’re using Vite, setting up Jest isn’t straightforward. In this guide, we’ll walk through the complete setup of Jest in a Vite + React project with Babel and React Testing Library.
Why Use Jest with Vite?
-
✅ Fast & reliable unit testing
-
✅ Works with React Testing Library for component tests
-
✅ Babel support for modern JavaScript & JSX
-
✅ Mocking CSS & file imports with identity-obj-proxy
Install Required Packages
Run the following commands in your project:
npm install --save-dev jest babel-jest @babel/preset-env @babel/preset-react identity-obj-proxy @testing-library/react @testing-library/jest-dom
npm install --save-dev jest-environment-jsdom
Configure Babel
Create a babel.config.js
file in your project root:
export default {
presets: [
['@babel/preset-env', { targets: { node: 'current' } }],
['@babel/preset-react', { runtime: 'automatic' }]
],
};
Configure Jest
Create jest.config.js
with the following:
export default {
testEnvironment: "jsdom",
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1",
"\\.(css|less|scss|sass)$": "identity-obj-proxy",
},
setupFilesAfterEnv: ["<rootDir>/src/setupTests.js"],
transform: {
"^.+\\.[jt]sx?$": "babel-jest",
},
};
Setup React Testing Library
Create src/setupTests.js
and include:
import '@testing-library/jest-dom';
Update ESLint Config
Enable Jest environment in eslint.config.js
:
Write Your First Test
Create a simple function and test it.
src/sum.js
export function sum(a, b) {
return a + b;
}
tests/unit/sum.test.js
import { sum } from '@/sum';
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
Update package.json Scripts
Add a test
script:
"scripts": {
"test": "jest"
}
Run Tests
Finally, run:
🎉 You should see PASS
for your test results.
Conclusion
That’s it! You now have Jest running inside your Vite + React project with support for Babel, Testing Library, and CSS modules. With this setup, you can confidently write tests for your components and functions, ensuring your app stays bug-free.