乐闻世界logo
搜索文章和话题

How to optimize Jest test performance? What methods can improve test speed?

2月19日 19:27

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:

javascript
jest.mock('./api', () => ({ fetchData: jest.fn(() => Promise.resolve('mocked data')) }));

5. Optimize Coverage Collection:

javascript
collectCoverageFrom: [ 'src/**/*.{js,jsx,ts,tsx}', '!src/**/*.stories.{js,jsx,ts,tsx}', '!src/**/*.d.ts' ],

6. Cache Optimization:

  • Jest automatically caches transformation results
  • Use --no-cache to disable cache (for debugging)
  • Clear cache: jest --clearCache

7. Reduce Unnecessary Tests:

  • Avoid over-testing
  • Skip slow tests: test.skip('slow test', () => { /* ... */ });
  • Use describe.skip to 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 --maxWorkers in CI to control resource usage
标签:Jest