79185854

Date: 2024-11-13 16:43:37
Score: 1
Natty:
Report link

Configuring Jest instead of Jasmine/Karma in Angular 18

1. Remover Jasmine y Karma (Remove Jasmine and Karma).

Run:

npm uninstall karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter jasmine core @types/jasmine 

2. Instalar las dependencias de Jest (Install Jest Dependencies).

npm install --save-dev jest@latest @types/jest@latest ts-jest@latest jest-preset-angular@latest

Nota: These dependencies are only for the development environment.


3. Crear archivo de configuración (Create configuration file) jest.config.js

The file must be created in the root of the project.

image1

Content of the file:

module.exports = {
  preset: 'jest-preset-angular',
  setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
  globalSetup: 'jest-preset-angular/global-setup',
};


4. Crear archivo de entorno de pruebas (Create test environment file) setup-jest.ts

The file must be created in the root of the project.

image2

Content of the file:

import 'jest-preset-angular/setup-jest';

5. Actualizar el archivo (Update the file) package.json

The property to edit is "scripts", adding the commands for running the tests with Jest.

  "scripts": {
      ...
     //Contenido generado por default del proyecto Angular
      ...
    "test":"jest",
    "test:watch": "jest --watch",
    "test:coverage": "jest --coverage"
  }

Quedará de la siguiente manera (Result):

image3


6. Modificar el archivo (Modify this file) tsconfig.spec.json

Make sure the file is configured correctly in order to use Jest.

Content of the file:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "types": [
      "jest",
    ],
    "module": "CommonJS"
  },
  "include": [
    "src/**/*.spec.ts",
    "src/**/*.d.ts"
  ]
}

image4


7. Probar que la configuración se realizó exitosamente (Test if the configuration was successful)

Run:

npm run test 

Si es un proyecto nuevo (con el contenido inicial generado por Angular) deberá ejecutarse sin errores:

image5


Para desplegar el porcentaje de covertura (Test coverage), ejecute:

npm run test:coverage 

Result:

image6


Para ejecutar Jest en modo de detección de cambios (watch mode):

npm run test:watch 

image7

 

Encuentra el repositorio con el proyecto de ejemplo (Find the repository with the example project)

https://github.com/joseOlivares/angular-jest

 

If you appreciate my effort,

:wave: please endorse my skills on Linkedin

 

:fire: More information about Jest, visit https://jestjs.io/docs/testing-frameworks

Reasons:
  • Blacklisted phrase (2): Crear
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: Luis Olivares