Angular Jest testing setup

An Angular application setup has unit testing configured with Karma and Jasmine by default. This post describes the steps to replace the default test setup width Jest.

  1.  Delete the packages that start with or contain jasmine or karma from the devDependencies section of the package.json file.
  2. Remove the “test” entry from the angular.json file.
  3. Delete the karma.config.js and the src/test.ts files.
  4. Install Jest:
    npm install --save-dev jest jest-preset-angular @types/jest
  5. Update the script in package.json to call Jest
    {
     ...
     "scripts": {
     ...
     "test": "jest",
     "test:watch": "jest --watch",
     ...
     },
     ...
    }
  6. Add script to import presets
    // src/setupJest.ts
    
    import 'jest-preset-angular';
  7. Add Jest config in package.json

    Make sure the path to your tsconfig.spec.ts file is correct.

    "jest": {
      "preset": "jest-preset-angular",
      "setupFilesAfterEnv": [
        "<rootDir>/src/setupJest.ts"
      ],
      "globals": {
        "ts-jest": {
          "tsConfig": "<rootDir>/tsconfig.spec.json",
          "stringifyContentPathRegex": "\\.html$",
          "astTransformers": [
            "jest-preset-angular/build/InlineFilesTransformer",
            "jest-preset-angular/build/StripStylesTransformer"
          ]
        }
      }
    }

    Make sure the paths to “setupFilesAfterEnv” and “tsConfig” are correct.
    Optionally a jest.config.js file could be added to override some of the base configurations from the jest-preset-angular package.

  8. Update the compilerOptions in the tsconfig.spec.json with the following entries:
    // tsconfig.spec.json{
      ...
      "compilerOptions": {
        "outDir": "./out-tsc/spec",
        "types": [
          // remove jasmine entry
          "jest",
          "node"
        ], 
        "emitDecoratorMetadata": true, 
        "esModuleInterop": true
      },
      "files": [
        // remove src/test.ts entry
        "src/polyfills.ts"
      ]
      ... 
    }
    

At this point, running npm test, should run using Jest and all of the tests should still pass.