Setting Jest in angular project
run npm i -D jest @types/jest jest-preset-angular
run npm uninstall -D jasmine @types/jasmine karma karma-jasmine karma-jasmine-html-reporter karma-phantomjs-launcher karma-sonarqube-unit-reporter
Delete src/test.ts, karma.conf.js
Create jest.setup.ts, jest.config.js at root folder level.
Content for jest.setup.ts:
import 'jest-preset-angular';
Object.defineProperty(window, 'CSS', {value: null});
Object.defineProperty(document, 'doctype', {
value: '<!DOCTYPE html>'
});
Object.defineProperty(window, 'getComputedStyle', {
value: () => {
return {
display: 'none',
appearance: ['-webkit-appearance']
};
}
});
/**
* ISSUE: https://github.com/angular/material2/issues/7101
* Workaround for JSDOM missing transform property
*/
Object.defineProperty(document.body.style, 'transform', {
value: () => {
return {
enumerable: true,
configurable: true,
};
},
});
Content for jest.config.js:
module.exports = {
"preset": "jest-preset-angular",
"setupFilesAfterEnv": [
"<rootDir>/jest.setup.ts"
],
"displayName": 'EBillingStatic',
"preset": 'ts-jest',
"roots": ['<rootDir>/src/app/'],
"collectCoverage": true,
"coverageReporters": ['html'],
"coverageDirectory": '<rootDir>/coverage',
"testMatch": ['**/+(*.)+(spec).+(ts)'],
//"testMatch": ['**/+(<your-spec-file-name>.)+(spec).+(ts)'], // to test single file
"globals": {
'ts-jest': {
tsConfig: '<rootDir>/src/tsconfig.spec.json',
stringifyContentPathRegex: '\\.html$',
astTransformers: [
'jest-preset-angular/build/InlineFilesTransformer',
'jest-preset-angular/build/StripStylesTransformer'
],
},
},
"transform": {
'^.+\\.(ts|js|html)$': 'ts-jest',
},
"moduleFileExtensions": ['ts', 'html', 'js', 'json'],
"moduleNameMapper": {
'^src/(.*)$': '<rootDir>/src/$1',
'^app/(.*)$': '<rootDir>/src/app/$1',
'^assets/(.*)$': '<rootDir>/src/assets/$1',
'^environments/(.*)$': '<rootDir>/src/environments/$1',
},
"transformIgnorePatterns": ['node_modules/(?!@ngrx)'],
"snapshotSerializers": [
'jest-preset-angular/build/AngularSnapshotSerializer.js',
'jest-preset-angular/build/HTMLCommentSerializer.js',
]
}
Update src/tsconfig.spec.json to :
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/spec",
"module": "commonjs",
"types": [
"jest",
"node"
],
"esModuleInterop": true,
"emitDecoratorMetadata": true
},
"files": [
"polyfills.ts"
],
"include": [
"**/*.spec.ts",
"**/*.d.ts"
]
}
Update 'test': 'ng test' to 'test': 'jest' in scripts of package.json
Optional: Delete projects.<your-app-name>.test as it is no longer needed.