nx: nx test: Jest unit tests are failing to run in any test that has been imported from other libraries.

Current Behavior

An NX - Ionic and Vue workspace fails to run tests, many solutions tested and any seems to fix the issue:

This is the error message:

  ● 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

Solutions tested:

Related Issues:

https://github.com/nrwl/nx/issues/8323 https://github.com/nrwl/nx/issues/7844 https://github.com/nrwl/nx/issues/8354 https://github.com/nrwl/nx/issues/9825 https://github.com/ionic-team/ionic-framework/issues/25223

Investigation made:

Expected Behavior

  • Ability to run any unit tests without issues
  • Ability to run the test without any other configuration to ignore patterns or support nx libraries

Steps to Reproduce

Here you can find a minimal repository to reproduce the issue:

https://github.com/marimendez88/of-jest-issue

  1. Create empty workspace: Run npx create-nx-workspace@^13.0.0
  2. select → apps option
  3. Install testing dependencies: npm install @nrwl/cypress@^13.0.0 @nrwl/jest@^13.0.0 @nrwl/linter@^13.0.0 --save-dev
  4. Install nx vue plugin : npm install @nx-plus/vue --save-dev
  5. Creating sample app: nx g @nx-plus/vue:app sample-app
  6. Install ionic npm i @ionic/vue npm i @ionic/vue-router
  7. Update main.ts under sample-app to use ionic
  8. Creating sample lib nx g @nx-plus/vue:lib sample-lib
  9. Create a header test component under sample-lib
  10. Import the header component into the sample app to use it
  11. Successfully served and components are shown as expected
  12. Run a test, error happens.

Failure Logs

This is the error message:

  ● 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:

    /of-jest-issue/apps/sample-app/src/components/HelloWorld.vue:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { defineComponent } from 'vue';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      1 | import { shallowMount } from '@vue/test-utils';
    > 2 | import HelloWorld from '../../src/components/HelloWorld.vue';
        | ^
      3 |
      4 | describe('HelloWorld.vue', () => {
      5 |   it('renders props.msg when passed', () => {

      at Runtime.createScriptFromCode (../../node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (tests/unit/example.spec.ts:2:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        5.015 s
Ran all test suites.

Environment

 >  NX   Report complete - copy this into the issue template

   Node : 14.17.1
   OS   : darwin x64
   npm  : 6.14.13

   nx : 13.10.3
   @nrwl/angular : Not Found
   @nrwl/cypress : 13.10.3
   @nrwl/detox : Not Found
   @nrwl/devkit : 13.10.3
   @nrwl/eslint-plugin-nx : 13.10.3
   @nrwl/express : Not Found
   @nrwl/jest : 13.10.3
   @nrwl/js : Not Found
   @nrwl/linter : 13.10.3
   @nrwl/nest : Not Found
   @nrwl/next : Not Found
   @nrwl/node : Not Found
   @nrwl/nx-cloud : Not Found
   @nrwl/nx-plugin : Not Found
   @nrwl/react : Not Found
   @nrwl/react-native : Not Found
   @nrwl/schematics : Not Found
   @nrwl/storybook : Not Found
   @nrwl/web : Not Found
   @nrwl/workspace : 13.10.3
   typescript : 4.6.4
   rxjs : 6.6.7
   ---------------------------------------
   Community plugins:
   	 @nx-plus/vue: 13.0.1

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 9
  • Comments: 29 (11 by maintainers)

Most upvoted comments

@BePasquet can you check your root jest.config.ts and make sure you have

import { getJestProjects } from '@nrwl/jest';

export default {
  projects: getJestProjects(),
};

and in your root jest.preset.js

const nxPreset = require('@nrwl/jest/preset').default; // note the .default here!

module.exports = { ...nxPreset };

Think I have the same error. I created a repository to reproduce starting from scratch with react. nx test gives the same SyntaxError: Cannot use import statement outside a module error. See https://github.com/Marcelh1983/nx-jest-error

Here’s what I had to do to get jest tests working after updating to ionic v6 using react in an nx project:

// <root>/apps/<app-name>/jest.config.js

const esModules = [
  '@ionic/core',
  '@stencil/core',
  'ionicons',
  '@ionic/react',
  '@ionic/react-router',
  '@ionic/react-test-utils',
].join('|');

module.exports = {
  displayName: 'tn-app',
  preset: '../../jest.preset.js',
  transform: {
    '^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': '@nrwl/react/plugins/jest',
    '^.+\\.[tj]sx?$': 'ts-jest',
  },
  transformIgnorePatterns: [
    `/node_modules/(?!${esModules})`,
    '/node_modules/@stencil/core/internal/app-data',
  ],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
  coverageDirectory: '../../coverage/apps/tn-app',
};

Update tsconfig to target es6:

// <root>/apps/<app-name>/tsconfig.json
{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    "jsx": "react-jsx",
    "allowJs": true,
    "skipLibCheck": true,
    "target": "es6",
    "lib": ["dom", "dom.iterable", "esnext", "es2017.object"],
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true
  },
  "include": ["src", "src/**/*.d.ts"],
  "references": [
    {
      "path": "./tsconfig.app.json"
    },
    {
      "path": "./tsconfig.spec.json"
    }
  ]
}

Did the same thing for libs in our nx monorepo

the reason the tests pass initially is more than likely the nx cloud cache just an FYI. you can check as it’ll say remote cache in the results @Xjph

Hi @barbados-clemens i updated the versions, added that code to the config and preset and is working thanks a lot for the help

"@nrwl/cli": "14.3.6",
"@nrwl/jest": "14.3.6",
"@nrwl/workspace": "14.3.6",
"@testing-library/react": "13.3.0",
"react-test-renderer": "18.2.0"

I’m going to ping some other people on the nx team that have windows machines to see if they can take a look if it is the OSes causing the issue. I’d be surprised if it was but it’s the only thing different that I can see. if it is. I imagine it might be a jest issue vs nx set up issue, but I’ll have to dig into it if we can reproduce it via WSL.

I can reproduce this with a new react workspace; following https://nx.dev/react-tutorial/01-create-application. Not even modifying any of the files; I added the transform ignore and allowJs flag to ./jest.config.ts and ./tsconfig.base.json, but I still get the same error.

  1. npx create-nx-workspace@latest
  2. Select react, less
  3. run nx test

https://nx.app/runs/rXGssNRGlFG

➜ nx test   

> nx run site:test

 FAIL   site  apps/site/src/app/app.spec.tsx
  ● 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:

    /home/matt/personal/website/apps/site/src/app/app.spec.tsx:4
    import { render } from '@testing-library/react';
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (../../node_modules/jest-runtime/build/index.js:1728:14)
      at TestScheduler.scheduleTests (../../node_modules/@jest/core/build/TestScheduler.js:333:13)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.564 s
Ran all test suites.
➜ nx report                      

 >  NX   Report complete - copy this into the issue template

   Node : 16.14.2
   OS   : linux x64
   npm  : 8.5.0
   
   nx : 14.1.4
   @nrwl/angular : Not Found
   @nrwl/cypress : 14.1.4
   @nrwl/detox : Not Found
   @nrwl/devkit : 14.1.4
   @nrwl/eslint-plugin-nx : 14.1.4
   @nrwl/express : Not Found
   @nrwl/jest : 14.1.4
   @nrwl/js : 14.1.4
   @nrwl/linter : 14.1.4
   @nrwl/nest : Not Found
   @nrwl/next : Not Found
   @nrwl/node : Not Found
   @nrwl/nx-cloud : 14.0.3
   @nrwl/nx-plugin : Not Found
   @nrwl/react : 14.1.4
   @nrwl/react-native : Not Found
   @nrwl/schematics : Not Found
   @nrwl/storybook : 14.1.4
   @nrwl/web : 14.1.4
   @nrwl/workspace : 14.1.4
   typescript : 4.6.4
   rxjs : 6.6.7
   ---------------------------------------
   Community plugins:

hey @barbados-clemens , thank you for the response, I have been looking at this error on Angular and React projects as well, the Comment from @Marcelh1983 has a react repo that reproduces the issue, I think I can find another time by end of this week to provide another repo in an angular project as well.

PD: I have been looking into this on existing repos, I have tried to implement that the docs point but the example given is not clear, if I try to import this: import { registerTsProject } from 'nx/src/utils/register'; immediately see an issue that the nx/src/… doesn’t exists.

Also, I followed the thread here as per your official issue closed 22 days ago, but, the repo is not accessible and the video doesn’t seem to help me either.