ESM Support
To use jest-preset-angular
with ESM support, you'll first need to check ESM Jest documentation.
jest-preset-angular
supports ESM via a ts-jest
config option useESM in combination with jest config option extensionsToTreatAsEsm.
There is also a preset to work with ESM.
We have example apps which contains base ESM setup to work with Jest and Angular.
Besides, there is setup-jest.mjs
to add to Jest setup file to ensure that Jest can set up test environment properly.
import 'jest-preset-angular/setup-jest.mjs';
Examples
Manual configuration
- JavaScript
- TypeScript
- JSON
module.exports = {
//...
extensionsToTreatAsEsm: ['.ts'],
globals: {
'ts-jest': {
tsconfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.html$',
useESM: true,
},
},
};
import type { Config } from 'jest';
const jestConfig: Config = {
//...
extensionsToTreatAsEsm: ['.ts'],
globals: {
'ts-jest': {
tsconfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.html$',
useESM: true,
},
},
};
export default jestConfig;
{
//...
"jest": {
"extensionsToTreatAsEsm": [".ts"],
"globals": {
"ts-jest": {
"tsconfig": "<rootDir>/tsconfig.spec.json",
"stringifyContentPathRegex": "\\.html$",
"useESM": true
}
}
}
}
Use ESM presets
Jest will attempt to load ESM files from node_modules
with default jest-resolve
which usually works for most of the cases.
However, there are cases like Angular libraries ESM built files or ESM files which are outside node_modules
might not be loaded
correctly.
To fix that, one can use moduleNameMapper
in jest config to instruct Jest to load the correct ESM files or create a
custom Jest resolver.
- JavaScript
- TypeScript
- JSON
module.exports = {
//...
preset: 'jest-preset-angular/presets/defaults-esm',
};
import type { Config } from 'jest';
const jestConfig = {
//...
preset: 'jest-preset-angular/presets/defaults-esm',
};
export default jestConfig;
// OR package.json
{
//...
"jest": {
"preset": "jest-preset-angular/presets/defaults-esm"
}
}