Skip to main content

Moving from Karma to Jest in Angular

00:03:24:59

With Karma being officially deprecated and no longer accepting new features or general bug fixes, it's time to consider migrating to Jest for Angular testing. This migration is particularly important for enterprise applications that need long-term support and modern testing capabilities. Let's explore how to make this transition smooth and efficient.

Why make the switch?

The decision to move from Karma to Jest is driven by several factors:

  • Karma is officially deprecated and will only receive critical security fixes
  • Jest offers faster test execution
  • Better snapshot testing capabilities
  • Improved debugging experience
  • Built-in code coverage reporting
  • Better integration with modern development tools

The migration process

1. Initial setup

Remove Karma-related dependencies and add Jest ones:

bash
npm uninstall karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter
npm install --save-dev jest @types/jest @angular-builders/jest

2. Configuration changes

Update the angular.json to use Jest instead of Karma:

json
{
  "projects": {
    "your-app": {
      "architect": {
        "test": {
          "builder": "@angular-builders/jest:run",
          "options": {
            "configPath": "jest.config.js"
          }
        }
      }
    }
  }
}

3. Jest configuration

Create a jest.config.js file in the project root:

typescript
import type { Config } from 'jest';

const config: Config = {
  clearMocks: true,
  collectCoverage: true,
  coverageDirectory: 'coverage',
  coverageProvider: 'v8',
  moduleNameMapper: {
    'src/(.*)$': '<rootDir>/src/$1',
    '@core/(.*)$': '<rootDir>/src/app/core/$1',
    '@shared/(.*)$': '<rootDir>/src/app/shared/$1',
    '@app/(.*)$': '<rootDir>/src/app/$1',
  },
  transformIgnorePatterns: ['node_modules/(?!@angular|rxjs.*)'],
  maxWorkers: 1,
  workerIdleMemoryLimit: '1GB',
};

export default config;

You can also create the jest.preset.js file using npx jest init command and then modify it to your needs.

For a detailed explanation regarding each configuration property and additional options, visit Jest documentation. You can also use jest-preset-angular to simplify the configuration.

4. Test file updates

Most existing tests will work with minimal changes. The main differences to be aware of are:

  • Using describe and it instead of describe and test
  • Slightly different syntax for mocking
  • Different approach to async testing

Optional 1: Adding HTML reporter

To make test results more readable and shareable, add the Jest HTML reporter:

bash
npm install --save-dev jest-html-reporter

Update the jest.config.js:

typescript
import type { Config } from 'jest';

const config: Config = {
  // ... existing config ...
  reporters: [
    'default',
    [
      './node_modules/jest-html-reporter',
      {
        pageTitle: 'Edge - UI Test Report',
      },
    ],
  ],
};

export default config;

Optional 2: TeamCity integration

For projects using TeamCity in their CI/CD pipeline, add the TeamCity reporter:

bash
npm install --save-dev jest-teamcity-reporter

Update the jest.config.js:

typescript
import type { Config } from 'jest';

const config: Config = {
  // ... existing config ...
  testResultsProcessor: 'jest-teamcity-reporter',
};

export default config;

Common challenges and solutions

During the migration, you might encounter these challenges:

  1. Async testing: Jest handles async testing differently than Karma. Update async test patterns to use Jest's async/await syntax.
  2. Mocking: Jest's mocking system is more powerful but different. Learn Jest's mocking patterns for better test isolation. If you have complex mocking with multiple dependencies, I highly recommend using the ng-mocks library, as it was very heplful for me.
  3. Test Environment: Tests relying on browser-specific features might need adjustments. Use Jest's DOM environment or jsdom when needed.

Expected benefits

After completing the migration, you can expect:

  • Reduced test execution time (typically 30-40% faster)
  • Better debugging experience with detailed error messages
  • Improved CI/CD pipeline integration
  • Better test coverage reporting
  • More maintainable test code

Conclusion

Migrating from Karma to Jest is a necessary step for Angular applications, especially given Karma's deprecation. While it requires some initial effort, the long-term benefits in terms of performance, maintainability, and developer experience make it a valuable investment.

For teams planning this migration, it's recommended to:

  1. Start with a small subset of tests to validate the approach
  2. Migrate tests incrementally
  3. Update CI/CD pipelines to support the new testing setup
  4. Train team members on Jest's features and best practices

Remember, testing is not just about writing tests - it's about having the right tools and processes in place to make testing efficient and effective. Jest provides the modern tooling needed for today's Angular applications.

Newesletter
Subscribe to get monthly updates with new articles