The original Karma runner in Angular uses a real browser for its tests, which can take a long time to spin up and run. This can be a burden as the longer the tests are, the more likely they are not to be run.

Jest uses NodeJS in order to perform testing, which makes it faster and therefore more suited for regular testing. As well, Jest has many more features which make it worthwhile.

We'll cover the migration for the project configuration as well as migrating existing tests.

Project configuration

Start by installing and removing the dependencies

npm install --save @types/jest jest-preset-angular
npm install --save-dev @angular-builders/jest jest
npm uninstall --save-dev karma karma-chrome-launcher karma-coverage-istanbul-reporter karma-jasmine karma-jasmine-html-reporter
rm src/karma.conf.js src/test.ts

Use the Jest runner instead of the Karma runner

{
    ...
    "projects": {
        ...
        "architect": {
            ...
            "test": {
                "builder": "@angular-builders/jest:run",

Add a new jest.config.js file

module.exports = {
    verbose: true,
    preset: 'jest-preset-angular',
    globals: {
      'ts-jest':{
        tsConfig: '<rootDir>/src/tsconfig.spec.json'
      }
    }
};

Update your tsconfig.json file to use Jest

{
    "compilerOptions": {
        ...
        "esModuleInterop": true,
        ...
         "types": ["jest"]

Update your tsconfig.spec.json file to use Jest

{
    ...
    "types": [
      "jest", // instead of jasmine
      ...
    ]
    ...
    "files": [
        // remove "test.ts"
    ]

Convert Jasmine mocks to Jest mocks

Perform the following replacements in order to migrate spy objects.

  • .and.returnValue(.mockImplementationOnce(() =>
  • with regex : jasmine\.createSpyObj\('\w+', \['(\w+)'\]\);{ $1: jest.fn() }

This can also be done with other jasmine objects as jest uses fn() to create mocks.