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.
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.
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):
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"
]
}
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:
Para desplegar el porcentaje de covertura (Test coverage), ejecute:
npm run test:coverage
Result:
Para ejecutar Jest en modo de detección de cambios (watch mode):
npm run test:watch
https://github.com/joseOlivares/angular-jest
:wave: please endorse my skills on Linkedin
:fire: More information about Jest, visit https://jestjs.io/docs/testing-frameworks