Copied!
React
Vite

Setup Jest in Vite React Project (Step-by-Step Guide)

setup-jest-in-vite-react-project-(step-by-step-guide)
Shahroz Javed
Oct 08, 2025 . 17 views

Table Of Contents

 

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?

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:

env: {
  jest: true,
},
    

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:

npm run test
    

🎉 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.

11 Shares

Similar Posts