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

Nx Angular: Jest encountered an unexpected token #11888

Closed
ibrahim-azez opened this issue Sep 6, 2022 · 7 comments
Closed

Nx Angular: Jest encountered an unexpected token #11888

ibrahim-azez opened this issue Sep 6, 2022 · 7 comments
Assignees
Labels
blocked: more info needed outdated scope: testing tools Issues related to Cypress / Jest / Playwright / Vitest support in Nx stale type: bug

Comments

@ibrahim-azez
Copy link

Current Behavior

My main app is giving me this error after testing.

I have seen this issue before but did not find any solution to it.

The failing 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:

    C:\Users\7078\Desktop\angular-whitelable\node_modules\lodash-es\lodash.js:10
    export { default as add } from './add.js';
    ^^^^^^

    SyntaxError: Unexpected token 'export'

      at Runtime.createScriptFromCode (../../node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (../../node_modules/ng2-charts/fesm2015/ng2-charts.mjs:5:23)

And my testing code for the main application is the following:


import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { RouterTestingModule } from '@angular/router/testing';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { AngularMaterialModule } from './core/angular-material.module';

import '@angular/localize/init';

describe('AppComponent', () => {
    let component: AppComponent;
    let fixture: ComponentFixture<AppComponent>;

    beforeEach(async () => {
        await TestBed.configureTestingModule({
            imports: [
                AngularMaterialModule,
                HttpClientTestingModule,
                ReactiveFormsModule,
                CommonModule,
                RouterTestingModule,
                BrowserAnimationsModule,
            ],
            declarations: [AppComponent],
        }).compileComponents();

        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create the app', () => {
        expect(component).toBeTruthy();
    });
});

My main application jest config

/* eslint-disable */
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',
    ],
};

And the default jest config for the whole workspace

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

export default {
  projects: getJestProjects(),
};

My core library is doing testing just fine

nx run core:test


 RUNS   core  libs/core/src/lib/services/range-selection.service.spec.ts
 RUNS   core  libs/core/src/lib/services/discount.service.spec.ts
...

Test Suites: 1 failed, 15 passed, 16 total

the jest config for the core library:

/* eslint-disable */
export default {
    displayName: 'core',
    preset: '../../jest.preset.js',
    setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
    globals: {
        'ts-jest': {
            tsconfig: '<rootDir>/tsconfig.spec.json',
            stringifyContentPathRegex: '\\.(html|svg)$',
        },
    },
    coverageDirectory: '../../coverage/libs/core',
    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',
    ],
};

Related Issues:

#10100

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

  1. Create empty workspace: Run npx create-nx-workspace
  2. select → apps option -> angular
  3. Creating sample lib npx nx generate @nrwl/angular:library test
  4. Run a test, error happens.

Failure Logs


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

    C:\Users\7078\Desktop\angular-whitelable\node_modules\lodash-es\lodash.js:10
    export { default as add } from './add.js';
    ^^^^^^

    SyntaxError: Unexpected token 'export'

      at Runtime.createScriptFromCode (../../node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (../../node_modules/ng2-charts/fesm2015/ng2-charts.mjs:5:23)

Environment

"dependencies": {
        "@angular/animations": "~14.0.0",
        "@angular/cdk": "^14.0.5",
        "@angular/common": "~14.0.0",
        "@angular/compiler": "~14.0.0",
        "@angular/core": "~14.0.0",
        "@angular/fire": "^7.4.1",
        "@angular/forms": "~14.0.0",
        "@angular/localize": "^14.0.7",
        "@angular/material": "^14.1.1",
        "@angular/material-moment-adapter": "^14.2.0",
        "@angular/platform-browser": "~14.0.0",
        "@angular/platform-browser-dynamic": "~14.0.0",
        "@angular/router": "~14.0.0",
        "@nrwl/angular": "14.4.3",
        "bootstrap": "^5.1.3",
        "chart.js": "^3.9.1",
        "chartjs-plugin-annotation": "^2.0.1",
        "chartjs-plugin-datalabels": "^2.1.0",
        "enhanced-resolve": "^5.10.0",
        "firebase": "^9.9.1",
        "highcharts": "^10.2.0",
        "moment": "^2.29.4",
        "ng2-charts": "^4.0.0",
        "path": "^0.12.7",
        "rxjs": "~7.4.0",
        "subsink": "^1.0.2",
        "tslib": "^2.0.0",
        "zone.js": "~0.11.4"
    },
    "devDependencies": {
        "@angular-devkit/build-angular": "^14.0.6",
        "@angular-eslint/eslint-plugin": "~14.0.0",
        "@angular-eslint/eslint-plugin-template": "~14.0.0",
        "@angular-eslint/template-parser": "~14.0.0",
        "@angular/cli": "~14.0.0",
        "@angular/compiler-cli": "~14.0.0",
        "@angular/language-service": "~14.0.0",
        "@nrwl/cli": "14.4.3",
        "@nrwl/cypress": "14.4.3",
        "@nrwl/eslint-plugin-nx": "14.4.3",
        "@nrwl/jest": "14.4.3",
        "@nrwl/linter": "14.4.3",
        "@nrwl/workspace": "14.4.3",
        "@types/jest": "^27.4.1",
        "@types/node": "16.11.7",
        "@typescript-eslint/eslint-plugin": "^5.29.0",
        "@typescript-eslint/parser": "^5.29.0",
        "autoprefixer": "^10.4.8",
        "cypress": "^9.1.0",
        "eslint": "~8.15.0",
        "eslint-config-prettier": "8.1.0",
        "eslint-plugin-cypress": "^2.10.3",
        "jest": "^27.5.1",
        "jest-preset-angular": "^11.0.1",
        "ng-packagr": "~14.0.0",
        "nx": "14.4.3",
        "postcss": "^8.4.14",
        "postcss-import": "~14.1.0",
        "postcss-preset-env": "~7.5.0",
        "postcss-url": "~10.1.3",
        "prettier": "^2.6.2",
        "tailwindcss": "^3.1.7",
        "ts-jest": "^27.1.4",
        "ts-node": "~10.8.0",
        "typescript": "~4.7.2"
    },
    "engines": {
        "node": "16.x.x"
    }
@barbados-clemens
Copy link
Contributor

barbados-clemens commented Sep 9, 2022

you'll have to transform any esm code to be used within jest since jest only uses cjs.

i.e.

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

there is a chance that lodash comes with a cjs version, if so you can just use the moduleNameMapper to tell jest to always use that version.

@barbados-clemens barbados-clemens self-assigned this Sep 9, 2022
@barbados-clemens barbados-clemens added the scope: testing tools Issues related to Cypress / Jest / Playwright / Vitest support in Nx label Sep 9, 2022
@ibrahim-azez
Copy link
Author

you'll have to transform any esm code to be used within jest since jest only uses cjs.

i.e.

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

there is a chance that lodash comes with a cjs version, if so you can just use the moduleNameMapper to tell jest to always use that version.

It has caused a lot of problems with my app.
Is there another solution?

@barbados-clemens
Copy link
Contributor

@ibrahim-azez what problems are you referencing? this is the default config that is generated (minus the lodash addition).

If it is now working and you are having a separate issue please close this issue and open a new one with other issues you're running into.

@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! 🙏

@github-actions github-actions bot added the stale label Apr 27, 2023
@shubh-tharani
Copy link

I have jest configured in package.json

"jest": {
"resetMocks": false,
"transform": {
"^.+\.(js|jsx)$": "babel-jest"
},
"transformIgnorePatterns": [
"/node_modules/(?!(@Shopify|d3-scale))/"
],
"coverageReporters": [
[
"lcov",
{
"projectRoot": "../../"
}
]
]
},

And I have configured babel.config.js

module.exports = {
presets: [
[
"@babel/preset-env",
{
targets: {
node: "current",
},
},
],
"@babel/preset-react",
],
};

I am getting this error while running the tests -

node_modules/d3-scale/src/index.js:1
({"Object.":function(module,exports,require,__dirname,__filename,global,jest){export {
^^^^^^

SyntaxError: Unexpected token 'export'

  at Runtime.createScriptFromCode (../../node_modules/jest-runtime/build/index.js:1350:14)
  at Object.<anonymous> (../../node_modules/@shopify/polaris-viz-core/build/cjs/utilities/createGradient.js:5:15)

If i remove the import of package @shopify/polaris-viz, the tests run successfully.
can somebody help me with this?

@github-actions github-actions bot removed the stale label May 10, 2023
@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! 🙏

@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 Jul 10, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
blocked: more info needed outdated scope: testing tools Issues related to Cypress / Jest / Playwright / Vitest support in Nx stale type: bug
Projects
None yet
Development

No branches or pull requests

3 participants