npm i -g @angular/cli
ng new angular-test-app
cd angular-test-app
ng serve --open
npm i --save-dev @testing-library/angular @testing-library/jest-dom
// Install the needed dependencies
npm i jest @types/jest jest-preset-angular --save-dev
// or
yarn add jest jest-preset-angular @types/jest --dev
npm uninstall karma karma-chrome-launcher karma-coverage-istanbul-reporter karma-jasmine karma-jasmine-html-reporter @types/jasmine @types/jasminewd2 jasmine-core jasmine-spec-reporter
// or
yarn remove karma karma-chrome-launcher karma-coverage-istanbul-reporter karma-jasmine karma-jasmine-html-reporter
rm karma.conf.js
Remove the test section from angular.json, this section looks like the following:
// angular.json
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": []
}
},
// REMOVE ALL "test" section
and Add to this file should have the following:
// setupJest.ts
import 'jest-preset-angular';
import 'jest-preset-angular/setup-jest';
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jest",
"node",
"@testing-library/jest-dom"
],
"esModuleInterop": true,
"emitDecoratorMetadata": true
},
"files": [
"src/polyfills.ts"
],
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}
"scripts": {
"test": "jest",
"test:coverage": "jest --coverage"
}
## Add to `package.json`
> Add Jest configuration to the end of this file
```js
"jest": {
"preset": "jest-preset-angular",
"setupFilesAfterEnv": [
"<rootDir>/setupJest.ts"
],
"testPathIgnorePatterns": [
"<rootDir>/node_modules/",
"<rootDir>/dist/"
],
"globals": {
"ts-jest": {
"tsconfig": "<rootDir>/tsconfig.spec.json",
"stringifyContentPathRegex": "\\.html$"
}
}
}
"compilerOptions": {
"allowSyntheticDefaultImports": true,
}
// tsconfig.spec.json
// add "@testing-library/jest-dom"
"types": [
"node",
"jest",
"@testing-library/jest-dom"
],
run the test for:
src/app/app.component.spec.ts
// run ones
yarn test
// or
npx jest
// watch for changes
yarn test --watch
// watch only one
yarn test async.component.spec.ts --watch
The coverage as built-in functionality is generated in:
./coverage
directory
The .compileComponents()
object is called to compile your component's resources like the template, styles, etc. You might not necessarily need to compile your component if you are using Webpack
.
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
}).compileComponents(); <-- Don't need it when using WebPack
}));
I'm a passionately curious Front-end Engineer. I like sharing what I know, and learning what I don't. London, UK.