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.
- Delete the packages that start with or contain jasmine or karma from the devDependencies section of the package.json file.
- Remove the “test” entry from the angular.json file.
- Delete the karma.config.js and the src/test.ts files.
- Install Jest:
npm install --save-dev jest jest-preset-angular @types/jest
- Update the script in package.json to call Jest
{ ... "scripts": { ... "test": "jest", "test:watch": "jest --watch", ... }, ... }
- Add script to import presets
// src/setupJest.ts import 'jest-preset-angular';
- 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 ajest.config.js
file could be added to override some of the base configurations from thejest-preset-angular
package. - Update the
compilerOptions
in thetsconfig.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.