VAN
DEL
.IO

Setup jest like a pro

🃏
I setup jest so rarely, and when i have to do it in a new poc project, i have to look up everything once again.
Angular version matching jest version, and oh jest-preset version.

So now i make my own reference for future me, maybe just writing this will make it stick!

 

Angular jest compatibility

ng@20 : jest@30 -> jest-preset-angular@15
ng@19 : jest@29 -> jest-preset-angular@14

Install jest and jest-preset-angular

npm install jest@version jest-preset-angular@version @types/jest@version --save-dev

Use npx to configure jest

npx jext --init

Would you like to use Jest when running “test” script in “package.json”?
Answer yes

Would you like to use Typescript for the configuration file?
Answer yes

Choose the test environment that will be used for testing
Answer jsdom (browser-like)

Do you want Jest to add coverage reports?
Answer yes

Which provider should be used to instrument code for coverage?
Answer v8

Automatically clear mock calls, instances, contexts and results before every test?
Answer yes

 

Create jest.config.ts – https://jestjs.io/docs/configuration

import type {Config} from 'jest';


const config: Config = {
preset:'jest-preset-angular',
setupFilesAfterEnv: ['/setup-jest.ts'],
testPathIgnorePatterns: ['/node_modules/', '/dist/'],
transform: {
'^.+\\.ts$':'ts-jest', // Only transform .ts files
},
transformIgnorePatterns: [
'/node_modules/(?!flat)/', // Exclude modules except 'flat' from transformation
],
};
export default config;

 

Edit test block angular.json

 "test": {
          "builder": "@angular-builders/jest:run",
          "options": {
            "configPath": "./jest.config.ts"
           
          }
        }
Ensure tsconfig.ts contains
"esModuleInterop": true,

 

Ensure tsconfig.spec.ts file contains


{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "types": ["jest", "node"]
  },
  "include": [
    "src/**/*.spec.ts",
    "src/**/*.d.ts"
  ]
}
Testing UI components
https://testing-library.com/docs/.
ng@20 : @testing-library/angular@18
ng>=17:@testing-library/angular@17
npm install --save-dev @testing-library/angular@version

Remove all traces of angular’s default testing, Jasmine & Karma

npm remove karma karma-chrome-launcher karma-jasmine karma-coverage karma-jasmine-html-reporterjasmine-core@types/jasmine