Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JEST failure while upgrading angular v13: SyntaxError: Unexpected token 'export' #7844

Closed
dean-g opened this issue Nov 22, 2021 · 56 comments
Closed
Labels

Comments

@dean-g
Copy link

dean-g commented Nov 22, 2021

Most of my JEST unit test cases are failing with the recent upgrade.

Please see below error message and advise,


 ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

Details:

    node_modules/d3-selection/src/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export {default as create} from "./create.js";
                                                                                      ^^^^^^

    SyntaxError: Unexpected token 'export'

    > 1 | import { Selection, select } from 'd3-selection';
        | ^
@dean-g
Copy link
Author

dean-g commented Nov 23, 2021

it looks my global (jest.preset.js) transformIgnorePatterns got skipped with the following new addition to jest.config.js

transformIgnorePatterns: ['node_modules/(?!.*.mjs$)'],

@Vchouliaras
Copy link

I got a similar error, after upgrading to latest version;

Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    .../node_modules/@angular/core/fesm2015/testing.mjs:7
    import * as i0 from '@angular/core';
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (../../node_modules/jest-runtime/build/index.js:1728:14)

transformIgnorePatterns: ['node_modules/(?!.*.mjs$)'], is not working for me though

@dean-g
Copy link
Author

dean-g commented Nov 23, 2021

I think the migration was not looking jest.preset.js file configuration. it was overriding global configuration. I have removed this setup and moved that into jest.preset.js global configuration file and it worked after that!.

Now, I am running into one last issue,

Jest has detected the following 2 open handles potentially keeping Jest from exiting:

● MESSAGEPORT

> 1 | import 'jest-preset-angular/setup-jest';

I am not sure why I am getting this issue.

@johannesnormannjensen
Copy link

johannesnormannjensen commented Nov 23, 2021

Got exactly the same error with a new nx workspace generated with npx create-nx-workspace

Though it wasn't with the latest version so I had to run the migrations.

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /home/johannes/projects/herewego/node_modules/@angular/core/fesm2015/testing.mjs:7
    import * as i0 from '@angular/core';
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (../../node_modules/jest-runtime/build/index.js:1728:14)

Running npx create-nx-workspace@latest seems to have working tests with jest!

@johannesnormannjensen
Copy link

Did some more digging!

It seems that migrating from an earlier workspace version bumps the version of some of the dependencies further than a fresh npx create-nx-workspace@latest :

ex. latest:


    "@angular/animations": "^13.0.0",
    "@angular/common": "^13.0.0",
    "@angular/compiler": "^13.0.0",
    "@angular/core": "^13.0.0",
    "@angular/forms": "^13.0.0",
    "@angular/platform-browser": "^13.0.0",
    "@angular/platform-browser-dynamic": "^13.0.0",
    "@angular/router": "^13.0.0",
    "@nrwl/angular": "13.2.2",

ex. Migrated workspace:

    "@angular/animations": "13.0.2",
    "@angular/common": "13.0.2",
    "@angular/compiler": "13.0.2",
    "@angular/core": "13.0.2",
    "@angular/forms": "13.0.2",
    "@angular/platform-browser": "13.0.2",
    "@angular/platform-browser-dynamic": "13.0.2",
    "@angular/router": "13.0.2",
    "@nrwl/angular": "13.2.2",

@johannesnormannjensen
Copy link

It seems that it has less to do with the version of the dependencies.
I'ts like @dean-g pointed out. The global jest.config.js has been altered during migration, but the the projects in the workspace have not had their jest.config.js altered with the new transformIgnorePatterns and transform configurations.

A migration step has gone wrong!

To fix this you have to update your jest.config.js files in all your projects yourself. Here's an example of how it should look in a library project:

module.exports = {
  displayName: "yourlibraryname",
  preset: '../../jest.preset.js',
  setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
  globals: {
    'ts-jest': {
      tsconfig: '<rootDir>/tsconfig.spec.json',
      stringifyContentPathRegex: '\\.(html|svg)$',
    },
  },
  coverageDirectory: '../../coverage/libs/yourlibraryname',
  transform: {
    '^.+\\.(ts|mjs|js|html)$': 'jest-preset-angular',
  },
  transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)'],
  snapshotSerializers: [
    'jest-preset-angular/build/serializers/no-ng-attributes',
    'jest-preset-angular/build/serializers/ng-snapshot',
    'jest-preset-angular/build/serializers/html-comment',
  ],
};

@leosvelperez
Copy link
Member

leosvelperez commented Nov 24, 2021

Thanks for reporting this!

Unfortunately, I couldn't reproduce the issue. I tried creating a new workspace using Nx v12.9.0 and then migrated it to the latest version. The migration was applied correctly to the project jest.config.js file.

Could you maybe create a minimal repo where the reported behavior can be reproduced? A repo in an older version where running the migration doesn't apply the expected changes.

FYI, the migration does the following:

  • Collects every project with a @nrwl/jest:jest executor.
  • Gets the jestConfig property from the executor configuration.
  • Reads the file specified in jestConfig.
  • If the jest-preset-angular text is found in the config (to identify the project is an Angular project), it applies the changes to have the right transform and transformIgnorePatterns.

@leosvelperez leosvelperez added blocked: repro needed scope: angular Issues related to Angular support in Nx labels Nov 24, 2021
@dlq84
Copy link

dlq84 commented Nov 24, 2021

I had a similar error, my jest.config.ts looked like this, and it had no changes after migration from 12 -> 13. Maybe having this original jest config helps with finding out what was going wrong.

module.exports = {
  displayName: 'client',
  preset: '../../jest.preset.js',
  setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
  globals: {
    'ts-jest': {
      stringifyContentPathRegex: '\\.(html|svg)$',
      tsconfig: '<rootDir>/tsconfig.spec.json',
    },
  },
  coverageDirectory: '../../coverage/apps/client',

  moduleNameMapper: {
    '^lodash-es$': 'lodash',
  },
  snapshotSerializers: [
    'jest-preset-angular/build/serializers/no-ng-attributes',
    'jest-preset-angular/build/serializers/ng-snapshot',
    'jest-preset-angular/build/serializers/html-comment',
  ],"transform": {"^.+\\.(ts|js|html)$":"jest-preset-angular"}
};

@leosvelperez
Copy link
Member

@dlq84 I added that exact configuration you shared to a project jest.config.js in a v12.9.0 workspace, ran the migrations and got the expected result:

diff --git a/apps/client/jest.config.js b/apps/client/jest.config.js
index 4040c4f..6497f93 100644
--- a/apps/client/jest.config.js
+++ b/apps/client/jest.config.js
@@ -18,5 +18,8 @@ module.exports = {
     'jest-preset-angular/build/serializers/ng-snapshot',
     'jest-preset-angular/build/serializers/html-comment',
   ],
-  transform: { '^.+\\.(ts|js|html)$': 'jest-preset-angular' },
+  transform: {
+    '^.+.(ts|mjs|js|html)$': 'jest-preset-angular',
+  },
+  transformIgnorePatterns: ['node_modules/(?!.*.mjs$)'],
 };

@leosvelperez
Copy link
Member

leosvelperez commented Nov 26, 2021

A note on the migration:

It's unfortunate you're having issues with the Jest setup. Unfortunately, the Angular 13 release broke compatibility with several tools (Jest among them) and this has caused a lot of trouble.

As Victor explained in #7613 (comment), automatic migrations are hard, not every workspace is the same or evolves in the same way and to account for every possible variation is just impossible. We try our best to provide the best migration experience possible, but there can definitely be scenarios we might miss or simply deviate from what we generate or expect to be generated.

For anyone coming to this particular issue, I described what the migration does in this comment #7844 (comment). I haven't been able to reproduce the issue you're having, so a minimal repo where the issue can be reproduced would help us to troubleshoot it.

If you're facing the issue, you need to make sure that your projects jest.config.js have these two properties with the following values:

module.exports = {
  ...
  transform: { '^.+.(ts|mjs|js|html)$': 'jest-preset-angular' },
  transformIgnorePatterns: ['node_modules/(?!.*.mjs$)'],
  ...
}

The gist of the change is that now Jest needs to process the .mjs files.

@GeorgeKnap
Copy link

GeorgeKnap commented Nov 26, 2021

A note on the migration:

It's unfortunate you're having issues with the Jest setup. Unfortunately, the Angular 13 release broke compatibility with several tools (Jest among them) and this has caused a lot of trouble.

As Victor explained in #7613 (comment), automatic migrations are hard, not every workspace is the same or evolves in the same way and to account for every possible variation is just impossible. We try our best to provide the best migration experience possible, but there can definitely be scenarios we might miss or simply deviate from what we generate to expect to be generated.

For anyone coming to this particular issue, I described what the migration does in this comment #7844 (comment). I haven't been able to reproduce the issue you're having, so a minimal repo where the issue can be reproduced would help us to troubleshoot it.

If you're facing the issue, you need to make sure that your projects jest.config.js have these two properties with the shown values:

module.exports = {
  ...
  transform: { '^.+.(ts|mjs|js|html)$': 'jest-preset-angular' },
  transformIgnorePatterns: ['node_modules/(?!.*.mjs$)'],
  ...
}

The gist of the change is that now Jest needs to process the .mjs files.

is it truly jest.config or the root jest.preset ? To me it looks like something should be in the root.
Also, how do we add to this the ignore patterns for things like lodash-es... ?

@leosvelperez
Copy link
Member

is it truly jest.config or the root jest.preset ? To me it looks like something should be in the root.

That's why I mentioned above every workspace is unique. You can have it in the root jest.preset.js and it will apply to every other jest.config.js that uses the preset (if it's not overwriting the config).

That's an example of a deviation of what we generate and what makes migrations to be hard. Nx workspaces can contain multiple technologies, therefore, we don't add configuration that might be Angular-specific at this point in time to the root configuration, we rather add it to the configuration of the Angular projects.

Also, how do we add to this the ignore patterns for things like lodah-es... ?

The transformIgnorePatterns property expects an array, you can pass multiple patterns to it. The pattern required to support Angular 13 is 'node_modules/(?!.*.mjs$)'. Besides that one you can have others you need.

@tomalaforge
Copy link
Contributor

tomalaforge commented Nov 26, 2021

I think the migration was not looking jest.preset.js file configuration. it was overriding global configuration. I have removed this setup and moved that into jest.preset.js global configuration file and it worked after that!.

Now, I am running into one last issue,

Jest has detected the following 2 open handles potentially keeping Jest from exiting:

● MESSAGEPORT

> 1 | import 'jest-preset-angular/setup-jest';

I am not sure why I am getting this issue.

After restoring all other jest.config file in all my libraries, I'm running in this same exact message when I run all my test with --detectOpenHandles

Which wasn't there on v12.

And I have no idea how this can be solved.
@dean-g did you find a solution?

@sergiocarneiro
Copy link

sergiocarneiro commented Nov 26, 2021

jest-preset-angular v11 describes a few changes that need to be performed:

Basically test-setup.ts becomes this:

module.exports = {
    displayName: "your-app-name-here",
    preset: "../../jest.preset.js",
    setupFilesAfterEnv: ["<rootDir>/src/test-setup.ts"],
    globals: {
        "ts-jest": {
            tsconfig: "<rootDir>/tsconfig.spec.json",
            stringifyContentPathRegex: "\\.(html|svg)$",
            useESM: true
        }
    },
    coverageDirectory: "../../coverage/apps/your-app-name-here",
    moduleFileExtensions: ["ts", "html", "js", "json", "mjs"],
    extensionsToTreatAsEsm: [".ts"],
    resolver: "jest-preset-angular/build/resolvers/ng-jest-resolver.js",
    transform: {
        "^.+\\.(ts|js|mjs|html|svg)$": "jest-preset-angular",
    },
    transformIgnorePatterns: [
        "node_modules/(?!.*\\.mjs$)"
    ],
    snapshotSerializers: [
        "jest-preset-angular/build/serializers/no-ng-attributes",
        "jest-preset-angular/build/serializers/ng-snapshot",
        "jest-preset-angular/build/serializers/html-comment",
    ],
};

Hopefully this helps someone, but for me, the issue has not been solved.

@Coly010
Copy link
Contributor

Coly010 commented Nov 29, 2021

@sergiocarneiro Another problem here is that you are changing the resolver that is being used:

    resolver: "jest-preset-angular/build/resolvers/ng-jest-resolver.js"

The jest-preset-angular resolver does not work in Nx Workspaces because it does not transform the TSConfig Path Aliases for libraries.

You need to remove that property and use the jest.preset.js that Nx generates for you at the workspace root, which is:

const nxPreset = require('@nrwl/jest/preset');

module.exports = { ...nxPreset };

Then your standard jest.config.js that lives within your app or library directory should look similar to this:

module.exports = {
  displayName: 'dashboard',
  preset: '../../jest.preset.js',
  setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
  globals: {
    'ts-jest': {
      tsconfig: '<rootDir>/tsconfig.spec.json',
      stringifyContentPathRegex: '\\.(html|svg)$',
    },
  },
  coverageDirectory: '../../coverage/apps/dashboard',
  transform: {
    '^.+\\.(ts|mjs|js|html)$': 'jest-preset-angular',
  },
  transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)'],
  snapshotSerializers: [
    'jest-preset-angular/build/serializers/no-ng-attributes',
    'jest-preset-angular/build/serializers/ng-snapshot',
    'jest-preset-angular/build/serializers/html-comment',
  ],
};

@achilehero
Copy link

@leosvelperez , the above PR is an example of migration that might help shed the light on some other issues that might be happening. Feel free to check it as a replication

@github-actions
Copy link

This issue has been automatically marked as stale because it hasn't had any recent activity. It will be closed in 14 days if no further activity occurs.
If we missed this issue please reply to keep it active.
Thanks for being a part of the Nx community! 🙏

@1antares1
Copy link

1antares1 commented Jan 2, 2022

Hi guys!

I tried to follow every comment with a possible solution here to the letter. I relied on an example project on github as well which works perfectly.

This also started to happen to me after updating everything manually.

My jest.config.js inside apps/my-app:

module.exports = {
    preset: "../../jest.preset.js",
    coverageDirectory: "../../coverage/apps/my-app",
    moduleFileExtensions: ["ts", "html", "js", "json", "mjs"],
    extensionsToTreatAsEsm: [".ts"],
    resolver: "jest-preset-angular/build/resolvers/ng-jest-resolver.js",
    setupFilesAfterEnv: ["<rootDir>/src/test-setup.ts"],
    globals: {
        "ts-jest": {
            tsconfig: "<rootDir>/tsconfig.spec.json",
            stringifyContentPathRegex: "\\.(html|svg)$",
            useESM: true
        }
    },
    transform: {
        "^.+\\.(ts|js|mjs|html|svg)$": "jest-preset-angular",
    },
    displayName: "my-app",
    snapshotSerializers: [
        "jest-preset-angular/build/serializers/no-ng-attributes",
        "jest-preset-angular/build/serializers/ng-snapshot",
        "jest-preset-angular/build/serializers/html-comment",
    ],
    transformIgnorePatterns: [
        "node_modules/(?!.*\\.mjs$)",
        "node_modules/(?!lodash-es)",
        "node_modules/(?!@ngrx|@ionic-native|@ionic)"
    ]
};

jest.config.js in the project root:

const { getJestProjects } = require("@nrwl/jest");

module.exports = { projects: getJestProjects() };

jest.preset.js in the root project:

const nxPreset = require("@nrwl/jest/preset");
module.exports = {
    ...nxPreset,
    testMatch: ["**/+(*.)+(spec|test).+(ts|js)?(x)"],
    transform: {
        "^.+\\.(ts|js|html)$": "ts-jest",
    },
    resolver: "@nrwl/jest/plugins/resolver",
    moduleFileExtensions: ["ts", "js", "html"],
    coverageReporters: ["html"],
};

package.json:

{
    "name": "my-app",
    "version": "1.1.10",
    "license": "MIT",
    "scripts": {
      ...
    },
    "private": true,
    "dependencies": {
        "@angular-devkit/architect": "0.1301.2",
        "@angular/animations": "13.1.0",
        "@angular/common": "13.1.0",
        "@angular/compiler": "13.1.0",
        "@angular/core": "13.1.0",
        "@angular/forms": "13.1.0",
        "@angular/platform-browser": "13.1.0",
        "@angular/platform-browser-dynamic": "13.1.0",
        "@angular/router": "13.1.0",
        "@angular/service-worker": "13.1.0",
        "@awesome-cordova-plugins/device": "5.37.2",
        "@ionic-enterprise/cordova": "9.0.3",
        "@ionic-native/app-version": "5.36.0",
        "@ionic-native/clipboard": "5.36.0",
        "@ionic-native/core": "5.36.0",
        "@ionic-native/fingerprint-aio": "5.36.0",
        "@ionic-native/in-app-browser": "5.36.0",
        "@ionic-native/ionic-webview": "5.36.0",
        "@ionic-native/secure-storage": "5.36.0",
        "@ionic-native/social-sharing": "5.36.0",
        "@ionic-native/splash-screen": "5.36.0",
        "@ionic-native/status-bar": "5.36.0",
        "@ionic-native/unique-device-id": "5.36.0",
        "@ionic/angular": "6.0.0",
        "@ionic/storage-angular": "3.0.6",
        "@ng-idle/core": "11.1.0",
        "@ng-idle/keepalive": "11.0.3",
        "@ngx-translate/core": "14.0.0",
        "@ngx-translate/http-loader": "7.0.0",
        "@sentry/angular": "6.16.1",
        "@sentry/tracing": "6.16.1",
        "cordova-android": "8.1.0",
        "cordova-plugin-device": "2.0.3",
        "cordova-plugin-inappbrowser": "5.0.0",
        "cordova-plugin-ionic-keyboard": "2.2.0",
        "cordova-plugin-ionic-webview": "5.0.0",
        "cordova-plugin-splashscreen": "6.0.0",
        "cordova-plugin-statusbar": "3.0.0",
        "cordova-plugin-whitelist": "1.3.5",
        "core-js": "3.19.3",
        "crypto-es": "1.2.7",
        "document-register-element": "1.14.10",
        "dom-to-image": "2.6.0",
        "lodash-es": "4.17.21",
        "moment": "2.29.1",
        "native-run": "1.5.0",
        "ng-circle-progress": "1.6.0",
        "node-forge": "0.10.0",
        "npm": "8.3.0",
        "reflect-metadata": "0.1.13",
        "rxjs": "7.4.0",
        "sass": "1.45.0",
        "tslib": "2.3.1",
        "uuid": "8.3.2",
        "zone.js": "0.11.4"
    },
    "devDependencies": {
        "@angular-architects/ddd": "1.5.1",
        "@angular-devkit/build-angular": "13.1.0",
        "@angular-eslint/builder": "13.0.1",
        "@angular-eslint/eslint-plugin": "13.0.1",
        "@angular-eslint/eslint-plugin-template": "13.0.1",
        "@angular-eslint/schematics": "13.0.1",
        "@angular-eslint/template-parser": "13.0.1",
        "@angular/cli": "13.1.0",
        "@angular/compiler-cli": "13.1.0",
        "@angular/language-service": "13.1.0",
        "@angularclass/hmr": "3.0.0",
        "@ionic/angular-toolkit": "5.0.3",
        "@ionic/cli": "6.18.1",
        "@nrwl/angular": "13.3.2",
        "@nrwl/cli": "13.3.1",
        "@nrwl/cypress": "13.3.1",
        "@nrwl/eslint-plugin-nx": "13.3.1",
        "@nrwl/jest": "13.3.1",
        "@nrwl/linter": "13.3.1",
        "@nrwl/node": "13.3.1",
        "@nrwl/workspace": "13.3.1",
        "@schematics/angular": "13.1.0",
        "@types/dom-to-image": "2.6.4",
        "@types/jest": "27.0.3",
        "@types/lodash-es": "4.17.5",
        "@types/node": "16.11.12",
        "@types/node-forge": "0.10.10",
        "@types/uuid": "8.3.3",
        "@typescript-eslint/eslint-plugin": "5.3.1",
        "@typescript-eslint/parser": "5.3.1",
        "codelyzer": "6.0.2",
        "compare-func": "2.0.0",
        "cordova": "10.0.0",
        "cordova-browser": "6.0.0",
        "cordova-clipboard": "1.3.0",
        "cordova-ios": "6.2.0",
        "cordova-plugin-add-swift-support": "2.0.2",
        "cordova-plugin-androidx": "3.0.0",
        "cordova-plugin-androidx-adapter": "1.1.3",
        "cordova-plugin-app-version": "0.1.12",
        "cordova-plugin-fingerprint-aio": "5.0.0",
        "cordova-plugin-iroot": " 3.1.0",
        "cordova-plugin-proguard": "2.2.0",
        "cordova-plugin-secure-storage-echo": " 5.1.1",
        "cordova-plugin-x-socialsharing": "6.0.3",
        "cordova-res": "0.15.4",
        "cordova-sqlite-storage": "6.0.0",
        "cordova-unique-device-id": "1.3.2",
        "cypress": "8.7.0",
        "dotenv": "10.0.0",
        "dtslint": "4.2.1",
        "es6-promise-plugin": "4.2.2",
        "eslint": "8.4.1",
        "eslint-config-prettier": "8.3.0",
        "eslint-plugin-cypress": "2.12.1",
        "eslint-plugin-prettier": "4.0.0",
        "fuzzy": "0.1.3",
        "inquirer": "8.2.0",
        "inquirer-autocomplete-prompt": "1.4.0",
        "jest": "27.4.5",
        "jest-preset-angular": "11.0.1",
        "ncu": "0.2.1",
        "ng-packagr": "13.1.0",
        "ngx-unused-css": "3.0.0",
        "npm-check-updates": "12.0.3",
        "npx": "10.2.2",
        "open": "8.4.0",
        "prettier": "2.5.1",
        "stylelint": "14.1.0",
        "stylelint-config-standard": "24.0.0",
        "ts-jest": "27.0.5",
        "ts-node": "9.1.1",
        "typescript": "^4.4.4",
        "webpack": "5.30.0",
        "xml2js": "0.4.23"
    },
    "description": "An ionic project",
    "browser": {
        "crypto": false,
        "stream": false
    },
    "cordova": {
        "plugins": {
            "cordova-plugin-ionic-keyboard": {},
            "cordova-plugin-splashscreen": {},
            "cordova-plugin-statusbar": {},
            "cordova-plugin-whitelist": {},
            "cordova-plugin-ionic-webview": {},
            "cordova-plugin-inappbrowser": {},
            "cordova-plugin-x-socialsharing": {
                "PHOTO_LIBRARY_ADD_USAGE_DESCRIPTION": "La aplicación requiere acceso a la biblioteca de fotos para funcionar apropiadamente.",
                "PHOTO_LIBRARY_USAGE_DESCRIPTION": "La aplicación requiere acceso a la biblioteca de fotos para funcionar apropiadamente."
            },
            "cordova-plugin-androidx": {},
            "cordova-plugin-androidx-adapter": {},
            "cordova-plugin-proguard": {},
            "cordova-sqlite-storage": {},
            "cordova-unique-device-id": {},
            "cordova-plugin-app-version": {},
            "cordova-plugin-fingerprint-aio": {
                "FACEID_USAGE_DESCRIPTION": " "
            },
            "cordova-plugin-secure-storage-echo": {},
            "cordova-plugin-iroot": {},
            "cordova-clipboard": {},
            "cordova-plugin-add-swift-support": {},
            "cordova-plugin-device": {}
        },
        "platforms": [
            "browser",
            "ios",
            "android"
        ]
    }
}

I still keep getting this error: :/

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    C:\Repos\temp-repos\my-app\node_modules\@angular\core\fesm2015\testing.mjs:7
    import { getDebugNode, RendererFactory2, ɵstringify, ɵReflectionCapabilities, Directive, Component, Pipe, NgModule, ɵgetInjectableDef, resolveForwardRef, ɵNG_COMP_DEF, ɵRender3NgModuleRef, ApplicationInitStatus, LOCALE_ID, ɵDEFAULT_LOCALE_ID, ɵsetLocaleId, ɵRender3ComponentFactory, ɵcompileComponent, ɵNG_DIR_DEF, ɵcompileDirective, ɵNG_PIPE_DEF, ɵcompilePipe, ɵNG_MOD_DEF, ɵtransitiveScopesFor, ɵpatchComponentDefWithScope, ɵNG_INJ_DEF, ɵcompileNgModuleDefs, NgZone, Compiler, COMPILER_OPTIONS, ɵNgModuleFactory, ModuleWithComponentFactories, InjectionToken, Injector, InjectFlags, ɵresetCompiledComponents, ɵflushModuleScopingQueueAsMuchAsPossible } from '@angular/core';       
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (../../node_modules/jest-runtime/build/index.js:1728:14)

Thansk for your replies.

@github-actions github-actions bot removed the stale label Jan 2, 2022
@danielraban
Copy link

Is there any solution to this?

@Coly010
Copy link
Contributor

Coly010 commented Jan 4, 2022

@1antares1
Similar to what I mentioned in this comment: #7844 (comment)
You have also set the resolver to use jest-preset-angular, which does not take into account the TS Path Mappings.

See this section of your jest.config.js

extensionsToTreatAsEsm: [".ts"],
resolver: "jest-preset-angular/build/resolvers/ng-jest-resolver.js",
setupFilesAfterEnv: ["<rootDir>/src/test-setup.ts"],    

If you can try to match the example config I gave in the above comment and see if that works for you :)

@Coly010
Copy link
Contributor

Coly010 commented Jan 17, 2022

Based on my previous response (#7844 (comment)), I'm going to close this issue.

The workaround listed here #7844 (comment) should be valid.

@GeorgeKnap
Copy link

I did as suggested above. Have the test-setup.ts with the import and this is the lib jest config

module.exports = {
  displayName: 'reports',
  preset: '../../jest.preset.js',
  setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
  globals: {
    'ts-jest': {
      tsconfig: '<rootDir>/tsconfig.spec.json',
      stringifyContentPathRegex: '\\.(html|svg)$',
    },
  },
  coverageDirectory: '../../coverage/libs/reports',
  transform: {
    '^.+\\.(ts|mjs|js|html)$': 'jest-preset-angular',
  },
  transformIgnorePatterns: [
    'node_modules/(?!.*\\.mjs$)',
    'node_modules/(?!@angular|@ngrx|@ngrx-translate|rxjs|countup.js|lodash-es|lodash)',
  ],
  snapshotSerializers: [
    'jest-preset-angular/build/serializers/no-ng-attributes',
    'jest-preset-angular/build/serializers/ng-snapshot',
    'jest-preset-angular/build/serializers/html-comment',
  ],
};

and yet it's the same error 🤷‍♂️ :

    Jest encountered an unexpected token

    Details:

    C:\development\SDS\core-ui-v3\node_modules\lodash-es\lodash.js:10
    export { default as add } from './add.js';
    ^^^^^^

    SyntaxError: Unexpected token 'export'

      3 | import { Actions, createEffect, EffectNotification, ofType, OnRunEffects } from '@ngrx/effects';
      4 | import { FFUFUsersApiService, FFuFUserService, UserEntity, UserField } from '@sds/api';
    > 5 | import { find } from 'lodash-es';

@joewIST
Copy link

joewIST commented Jan 19, 2022

@GeorgeKnap i had the same issue but i managed to fix it by making the transformIgnorePatterns an array containing a single string, rather an array of multiple strings

@GeorgeKnap
Copy link

@GeorgeKnap i had the same issue but i managed to fix it by making the transformIgnorePatterns an array containing a single string, rather an array of multiple strings

Could you share an example please? I'm not good with these regular expressions that seems to be used there.

@eweap
Copy link
Contributor

eweap commented Jan 19, 2022

@GeorgeKnap i had the same issue but i managed to fix it by making the transformIgnorePatterns an array containing a single string, rather an array of multiple strings

Thanks for the tip @joewIST !
There seems to be a bug with transformIgnorePatterns containing multiple entries (or am I misunderstanding the rule ?)

I changed:

transformIgnorePatterns: [
    'node_modules/(?!.*\\.mjs$)',
    'node_modules/(?!@angular|@ngneat/spectator|array-move|lodash-es)',
],

with:

transformIgnorePatterns: [
    `node_modules/(?!@angular|@ngneat/spectator|array-move|lodash-es)`,
],

and the error was gone !

@GeorgeKnap
Copy link

Confirmed! Error is gone when used just one line 🥳

@ajsaraujo
Copy link
Contributor

ajsaraujo commented Mar 15, 2022

This StackOverflow answer did it for me. I made a script to update all my jest.config.js files, I'll leave it here since it can be useful for someone. Note that you also have to update the dependencies, as stated in the answer.

@RAlhawash
Copy link

if someone is still having issues, add <rootDir> at the beginning of transformIgnorePatterns path, especially jest.config.js files inside libs, if the lib generator doesn't add it.
e.g.

transformIgnorePatterns: ['<rootDir>/node_modules/(?!.*\\.mjs$)'],

@jericirenej
Copy link

jericirenej commented May 20, 2022

I found that adding the rootDir makes the initial test runs very long for each test file. For me, the performacne was quicker, if I changed the transformIgnorePatters entry to a regex string:
transformIgnroePatterns: ['/node_modules(?!.*.mjs$)/']

@cjoecker
Copy link

In my case, not only the .mjs files were generating an error.
Hence, this in jest.config.ts file fixed the problem:

// Modules throwing error "Jest encountered an unexpected token"
const esModules = ['@angular', 'tslib', 'rxjs'];

export default {
  ...
  transformIgnorePatterns: [
    `<rootDir>/node_modules/(?!.*\\.mjs$|${esModules.join('|')})`,
  ],
};

@Rezi
Copy link

Rezi commented Jul 20, 2022

had same issue when creating brand new nx project with angular 14. Looks like the jest config is set up correctly for apps, but are wrongly set for libraries generated with nx. I just copied the app config settings to the libraries as well and all works well now

@CharlieGreenman
Copy link

For what it's worth, I think a more efficient approach is to mock out the service all together such as

jest.mock('nanoid', () => ({
    __esModule: true, // this property makes it work
    default: 'mockedDefaultExport',
    namedExport: jest.fn(),
}));

in the test-setup.ts file. Then make an Angular wrapper service for the esm service. You can then mock out in your unit tests. Jest configs can then remain the same.

@Darko1996
Copy link

In my case, not only the .mjs files were generating an error. Hence, this in jest.config.ts file fixed the problem:

// Modules throwing error "Jest encountered an unexpected token"
const esModules = ['@angular', 'tslib', 'rxjs'];

export default {
  ...
  transformIgnorePatterns: [
    `<rootDir>/node_modules/(?!.*\\.mjs$|${esModules.join('|')})`,
  ],
};

thank youuu! this worked for me

@karim-ch
Copy link

karim-ch commented Sep 5, 2022

Just updating my node JS to version 16 or later solved my issue

@ldco2016
Copy link

ldco2016 commented Sep 12, 2022

@johannesnormannjensen

I attempted to implement your version of jest.config.ts, but I still get the error:

 >  NX   Failed to run update-jest-preset-angular-8-4-0 from @nrwl/jest. This workspace is NOT up to date!


 >  NX   Cannot find module '/Users/ldco2016/Projects/<project-name>/apps/<project-backend-name>/jest.config.js'

These are my devDependencies:

    "@nrwl/angular": "14.7.0",
    "@nrwl/cli": "14.7.0",
    "@nrwl/eslint-plugin-nx": "14.7.0",
    "@nrwl/jest": "14.7.0",
    "@nrwl/linter": "14.7.0",
    "@nrwl/nest": "14.7.0",
    "@nrwl/node": "14.7.0",
    "@nrwl/workspace": "14.7.0",

I am on Node v16.16.0

@neeeekto
Copy link

Hi
I have same problem with react project(
https://github.com/neeeekto/nx-react-comp-lib-err

If I run tests for "components" library I get this error.

@mi-martinez
Copy link

transformIgnorePatterns: ['/node_modules/(?!.*\.mjs$)'],

Esta funcioino para mi en NX

@eggei
Copy link

eggei commented Dec 23, 2022

If you are here and not Angular but React like me, check this one: #8323

@quicksilverr
Copy link

I'm getting this error,

import _async_to_generator from "@swc/helpers/src/_async_to_generator.mjs";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:360:18)
at wrapSafe (node:internal/modules/cjs/loader:1094:15)
at Module._compile (node:internal/modules/cjs/loader:1129:27)
at Module._compile (/Users/symplrr/Desktop/Projects/Backend/zonocloud-monorepo/node_modules/pirates/lib/index.js:136:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1219:10)
at Object.newLoader [as .ts] (/Users/symplrr/Desktop/Projects/Backend/zonocloud-monorepo/node_modules/pirates/lib/index.js:141:7)
at Module.load (node:internal/modules/cjs/loader:1043:32)
at Function.Module._load (node:internal/modules/cjs/loader:878:12)
at Module.require (node:internal/modules/cjs/loader:1067:19)
at require (node:internal/modules/cjs/helpers:103:18)

While building a nx-plugin

@github-actions
Copy link

This issue has been closed for more than 30 days. If this issue is still occuring, please open a new issue with more recent context.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Mar 20, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests