Optimizing Jest test performance can improve development efficiency and CI/CD speed:
1. Parallel Test Execution: Jest runs tests in parallel by default, significantly improving speed. Ensure tests are independent.
2. Selective Test Running:
bash# Run tests only for changed files jest --onlyChanged # Run tests matching pattern jest --testPathPattern=auth # Use .only to temporarily run specific tests test.only('specific test', () => { /* ... */ });
3. Optimize Test Environment:
javascript// jest.config.js module.exports = { testEnvironment: 'node', // Faster than jsdom maxWorkers: '50%', // Limit worker processes testTimeout: 5000, // Set reasonable timeout };
4. Use Mocks to Reduce External Dependencies:
javascriptjest.mock('./api', () => ({ fetchData: jest.fn(() => Promise.resolve('mocked data')) }));
5. Optimize Coverage Collection:
javascriptcollectCoverageFrom: [ 'src/**/*.{js,jsx,ts,tsx}', '!src/**/*.stories.{js,jsx,ts,tsx}', '!src/**/*.d.ts' ],
6. Cache Optimization:
- Jest automatically caches transformation results
- Use
--no-cacheto disable cache (for debugging) - Clear cache:
jest --clearCache
7. Reduce Unnecessary Tests:
- Avoid over-testing
- Skip slow tests:
test.skip('slow test', () => { /* ... */ }); - Use
describe.skipto skip entire test suites
8. Watch Mode Optimization:
bash# Use --watchAll to watch all files jest --watchAll # Use --watch to watch only related files jest --watch
Best Practices:
- Keep tests fast and independent
- Use mocks to isolate external dependencies
- Regularly review and optimize slow tests
- Use
--maxWorkersin CI to control resource usage