Setting Up Jest
One thing that confused me when I first started was all the configuration files. Why do I need a jest.config.js? Can I not just install it and go? Let me save you the headache and show you the simplest way to get Jest running.
Here is the thing. Jest works great with zero configuration for simple projects. But a few tweaks can make your life way easier as your project grows.
Installation
Open your terminal and install Jest as a dev dependency. You do not want Jest in your production bundle.
npm install --save-dev jest
That installs Jest and adds it to your devDependencies in package.json. Simple enough.
Package.json Scripts
Add a test script to your package.json. This is the command you will run to execute your tests.
{
"name": "my-project",
"scripts": {
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage"
},
"devDependencies": {
"jest": "^29.0.0"
}
}
Now you can run npm test to run all tests once, or npm run test:watch to re-run tests every time you save a file. That watch mode is a game changer for productivity.
Jest Config File
For most projects, you do not need a config file. But if you want to customize things like where Jest looks for tests or how it handles modules, create a jest.config.js in your project root.
// jest.config.js
module.exports = {
testEnvironment: 'node',
coverageDirectory: 'coverage',
collectCoverageFrom: [
'src/**/*.js',
'!src/**/*.test.js'
],
verbose: true
};
The testEnvironment tells Jest where your code runs. Use node for backend code and jsdom if you need to test browser stuff. The collectCoverageFrom tells Jest which files to include in coverage reports.
Try it Yourself →Key Takeaways
- Install Jest with npm install --save-dev jest
- Add test scripts to package.json for easy running
- Use test:watch mode to re-run tests automatically as you code
- Jest works with zero config for simple projects
- Create jest.config.js only when you need custom settings