Search code examples
angularjestjsionic-nativeionic4

Jest/Ionic 4 beta - import { Platform } from '@ionic/angular'; gets SyntaxError: Unexpected token export in Jest testing, not Ionic


When running Jest against the base package, I get an error in Jest in running the test, which does not appear when simply running ionic serve. Jest gets an error on

import { Platform } from '@ionic/angular';

which is:

export { IonicModule } from './ionic-module';
^^^^^^

SyntaxError: Unexpected token export

  3 | import { RouterTestingModule } from '@angular/router/testing';
  4 |
> 5 | import { Platform } from '@ionic/angular';
    | ^
  6 | import { SplashScreen } from '@ionic-native/splash-screen/ngx';
  7 | import { StatusBar } from '@ionic-native/status-bar/ngx';
  8 |

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
  at Object.<anonymous> (src/app/app.component.spec.ts:5:1)

My Jest.config.json

module.exports = {
    collectCoverage: true,
    collectCoverageFrom: [
        "src/**/*.ts"
    ],
    coverageDirectory: "<rootDir>/coverage/",
    moduleNameMapper: {
        "@core/(.*)": "<rootDir>/src/app/core/$1",
        "@state/(.*)": "<rootDir>/src/app/state/$1"
    },
    preset: "jest-preset-angular",
    roots: ['src'],
    setupTestFrameworkScriptFile: "<rootDir>/src/setup-jest.ts",
    transformIgnorePatterns: [
        "node_modules/(?!(@ionic-native|@ionic|angularfire2)/)"
    ],
    verbose: false  
}

I am just using the sample side menu template and adjusting the components to run Jest.


Solution

  • Seeing all answers being quite long I have decided to give show what worked for me after reading Jest unit testing no longer works with Ionic 4.

    To make it work you need to add to jest.config.ts:

    transformIgnorePatterns: [
      "node_modules/(?!@ionic-native|@ionic)"
    ],
    

    And in tsconfig.spec.json set:

    "compilerOptions": {
      "allowJs": true,
    },