I'm trying to use jest to test an Ionic app. My jest configuration is:
preset: 'jest-preset-angular',
setupTestFrameworkScriptFile: '<rootDir>/src/setupJest.ts',
transformIgnorePatterns: ['node_modules/(?!@ngrx|@ionic-native|@ionic)'],
globals: {
__TRANSFORM_HTML__: true,
},
The setupJest.js
file has import 'jest-preset-angular';
.
I have a very simple test where I use TestBed to create an instance of the App component and check that it's truthy. In this code I have import { Platform } from '@ionic/angular';
.
Jest errors with:
Cannot find module '@ionic/angular' from 'app.component.test.ts'
If I just remove the import { Platform } from '@ionic/angular'
from the test file, Jest gives me the same error from the component file:
Cannot find module '@ionic/angular' from 'app.component.ts'
Using ionic serve
/ building works, jest is just giving me this error that it can't import X from Y.
How can I get jest to import from @ionic
files?
I was able to resolve this from the information in the linked GitHub issue. I arrived at the final configurations linked here: https://github.com/ionic-team/ionic/issues/15695#issuecomment-428412641
Since, I have modified these configurations to speed up the tests (with cache) and still have not run into issues. My current configurations:
// jest.config.js
module.exports = {
globals: {
// jest-preset-angular sets ts-jest tsConfigFile as "src/tsconfig.spec.json". This overwrites
// it to use the default `tsconfig.json`. You can change this to your preferred config.
__TRANSFORM_HTML__: true,
},
preset: 'jest-preset-angular',
setupTestFrameworkScriptFile: '<rootDir>/src/setupJest.ts',
moduleNameMapper: {
'^@ionic/core/loader': '<rootDir>/node_modules/@ionic/core/dist/esm/es5/ionic.define.js',
},
transformIgnorePatterns: [
'<rootDir>/node_modules/(?!@ionic)',
],
};
src/setupJest.ts
only includes import 'jest-preset-angular'
.
TypeScript configuration:
{
"compilerOptions": {
"allowJs": true,
"target": "esnext",
"module": "commonjs",
"moduleResolution": "node",
"declaration": false,
"noUnusedLocals": true,
"noUnusedParameters": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"skipLibCheck": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": ["es6", "dom"]
}
}
You can probably vary some of these configuration settings quite a bit, but the most important one is allowJs
. This is required or else jest
won't be able to import a lot of the Ionic libraries properly.
Finally, remember to import from /ngx
with Ionic 4 files. For example:
import { StatusBar } from '@ionic-native/status-bar/ngx';
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments