Description
I think this not a secret that "Angular + Jest" isn't a popular solution. So it's quite hard to find any information in the internet if you face any problems.
I have a quite big project, (about 30mb in mono-repo) and while migrating to Jest I faced lot of issues which not described anywhere in the internet.
So my proposal, we can create a Wiki page on this github and start gather issues with solutions. To make use of Jest + Angular delightful and painless.
I can start from some:
-
Q:
ReferenceError: CSS is not defined
when testing components which used Material Design lib.A: Material Design library has a special check whether it run in browser environment or not. This check fails in
jsdom
, environment, because it's emulate browser, but not for all cases.
add this to setup-jest.ts
Object.defineProperty(window, 'CSS', {value: () => ({})});
-
Q:
Could not find Angular Material core theme..
orCould not find HammerJS
when testing components which used Material Design lib.A: There few possible solutions, but most bulletproof:
add this to setup-jest.ts
const WARN_SUPPRESSING_PATTERNS = [
/Could not find Angular Material core theme/,
/Could not find HammerJS/,
];
const warn = console.warn;
Object.defineProperty(console, 'warn', {
value: (...params: string[]) => {
if (!WARN_SUPPRESSING_PATTERNS.some((pattern) => pattern.test(params[0]))) {
warn(...params);
}
}
});
3: Q: When run with coverage get this errors
No file coverage available for: c:\projects\meteoguard\src\app\tasks\shared\index.ts
at CoverageMap.fileCoverageFor (node_modules/istanbul-lib-coverage/lib/coverage-map.js:96:15)
A: this errors appears only for index.ts files which has only import/export statements,actually I don't know why it happens (may be typescript compilation output is empty for this files), but as a workaround you can just add this index.ts
files to coverage ignore pattern. Even more, this index.ts
files don't have any value for coverage
package.json
"jest": {
"coveragePathIgnorePatterns": [
"/node_modules/",
"index.ts"
],
},
- Q: "Syntax Error: Invalid or unexpected token" with absolutely unhelpful stack trace.
A: Probably there is a require of file type which is not supported by Jest itself. For instance "png".
Follow jest documentation: https://facebook.github.io/jest/docs/en/webpack.html#content