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

[Bug]: SyntaxError: Cannot use import statement outside a module #1149

Closed
Mawi137 opened this issue Nov 8, 2021 · 16 comments · Fixed by #1151
Closed

[Bug]: SyntaxError: Cannot use import statement outside a module #1149

Mawi137 opened this issue Nov 8, 2021 · 16 comments · Fixed by #1151

Comments

@Mawi137
Copy link

Mawi137 commented Nov 8, 2021

Version

11.0.0-rc.2

Steps to reproduce

Steps to reproduce:

Expected behavior

No error

Actual behavior

After updating to @ngx-translate/core@14.0.0, I keep getting this error in my jest tests (application itself works fine):

C:\dev\prj\Angular13Test\node_modules\@ngx-translate\core\fesm2015\ngx-translate-core.mjs:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import * as i0 from '@angular/core';
                                                                                                                                           ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      1 | import { Component } from '@angular/core';
    > 2 | import {TranslateService} from '@ngx-translate/core';
        | ^
      3 |
      4 | @Component({
      5 |   selector: 'app-root',

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (src/app/app.component.ts:2:1)

Any idea what the issue might be?
I also created a simple new Angular project, added ngx-translate + jest and added the TranslateService in the constructor of the AppComponent. It has the same issue.

Additional context

No response

Environment

System:
    OS: macOS 11.6
    CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
  Binaries:
    Node: 14.17.0 - /usr/local/bin/node
    Yarn: 1.19.1 - /usr/local/bin/yarn
    npm: 7.15.1 - /usr/local/bin/npm
  npmPackages:
    jest: ^27.3.1 => 27.3.1
@ahnpnl
Copy link
Collaborator

ahnpnl commented Nov 8, 2021

You need to add @ngx-translate/core to transformIgnorePatterns like this

transformIgnorePatterns: ['node_modules/(?!@angular|@ngx-translate)'],

Angular 13 libraries are shipped under ESM format I believe, which now only contains .mjs files. Jest doesn't understand .mjs files in CommonJS mode therefore you need to inform Jest to transform it.

@Mawi137
Copy link
Author

Mawi137 commented Nov 8, 2021

Thanks, that seems to do the trick!

@FrozenPandaz
Copy link
Contributor

FYI: The following pattern will not ignore (transform with jest-preset-angular) any .mjs files in node_modules which would better describe the growing set of packages with the new APF format in Angular 13.

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

@ahnpnl
Copy link
Collaborator

ahnpnl commented Nov 9, 2021

I think that pattern seems to be generic enough to add to the preset?

@TCModus
Copy link

TCModus commented Nov 17, 2021

@ahnpnl or @FrozenPandaz 's solution is not working for me. I am using Nx and angular 13. I have an angular library in the Nx workspace that utilizes the ngx-translate library which is working when I serve the app in the workspace but the libraries jest tests fail for the components using either the translate service or pipe.
My libraries jest.config.js file is as follows:
`
module.exports = {

displayName: 'ui',

preset: '../../jest.preset.js',

setupFilesAfterEnv: ['/src/test-setup.ts'],

globals: {

'ts-jest': {

  tsconfig: '<rootDir>/tsconfig.spec.json',

  stringifyContentPathRegex: '\\.(html|svg)$',

},

},

coverageDirectory: '../../coverage/libs/ui',

transformIgnorePatterns: [

'../../node_modules/(?!.*\\.mjs$)'

],

transform: {

'^.+\\.(ts|js|html)$': 'jest-preset-angular',

},

snapshotSerializers: [

'jest-preset-angular/build/serializers/no-ng-attributes',

'jest-preset-angular/build/serializers/ng-snapshot',

'jest-preset-angular/build/serializers/html-comment',

],

};
`

I have also tried specifying the path to node_modules as 'node_modules/(?!.\.mjs$)' and '/node_modules/(?!.\.mjs$)' also with no success. What I am seeing is anytime a components spec file references the @ngx-translate library at all in any way Jest will of course fail in parsing the .mjs file in the ngx-library with the error:
node_modules/@ngx-translate/core/fesm2020/ngx-translate-core.mjs:1 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import * as i0 from '@angular/core';
I know Jest does not work with mjs files however why is my transformIgnorePattern option not working? Been banging my head on this issue for longer than I care to admit so any help is much appreciated thanks!

@ahnpnl
Copy link
Collaborator

ahnpnl commented Nov 17, 2021

@TCModus the workaround will be applicable to jest-preset-angular at next tag, which is 11.0.0-rc.4. Since you are using Nx, you should wait until Nx releases a new version which supports Angular 13 fully.

@achilehero
Copy link

achilehero commented Dec 8, 2021

Hi all!
Should this work for nx now? Cause for me it doesn't seem to.
I tried everything from https://thymikee.github.io/jest-preset-angular/docs/guides/angular-13+/ but with no success.

@wtho
Copy link
Collaborator

wtho commented Dec 8, 2021

@achilehero This is an issue with nx. Please follow the following issue: nrwl/nx#7844

@achilehero
Copy link

Yes, thanks! I discovered that after I asked here.

@DamianArado
Copy link

If anyone is still facing this error.

I'm using Jest 28 and Angular 13 with jest-preset-angular 12 and the solution was having transformIgnorePatterns in a single line if you are using a single module in it, for ex., node_modules.

jest.config.js:

// modules inside node_modules throwing error: cannot use import statement
const esModules = ['@angular', '@ngrx', 'three'];
---------------
transformIgnorePatterns: [
    `/node_modules/(?!.*\\.mjs$|${esModules.join('|')})`,
],
-----------------

and then hopefully, all the .mjs files inside node_modules in CommonJS mode will be taken into account by Jest.

@Mawi137
Copy link
Author

Mawi137 commented Jul 28, 2022

This is also a good lib to integrate Jest into your Angular project: https://www.npmjs.com/package/@angular-builders/jest

@klevismehmeti
Copy link

klevismehmeti commented Aug 2, 2022

upgraded to angular 14, and i have this problem:
`Details:

/Users/user1/Documents/core-obg-ngx-packages-core/node_modules/@angular/core/fesm2020/testing.mjs:7
import { getDebugNode as getDebugNode$1, RendererFactory2 as RendererFactory2$1, ɵstringify, ɵReflectionCapabilities, Directive, Component, Pipe, NgModule, ɵgetInjectableDef, resolveForwardRef as resolveForwardRef$1, ɵNG_COMP_DEF, ɵRender3NgModuleRef, ApplicationInitStatus, LOCALE_ID as LOCALE_ID$1, ɵ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 as InjectionToken$1, Injector as Injector$1, InjectFlags as InjectFlags$1, ɵsetAllowDuplicateNgModuleIdsForTest, ɵresetCompiledComponents, ɵsetUnknownElementStrictMode as ɵsetUnknownElementStrictMode$1, ɵsetUnknownPropertyStrictMode as ɵsetUnknownPropertyStrictMode$1, ɵgetUnknownElementStrictMode as ɵgetUnknownElementStrictMode$1, ɵgetUnknownPropertyStrictMode as ɵgetUnknownPropertyStrictMode$1, ɵflushModuleScopingQueueAsMuchAsPossible } from '@angular/core';
^^^^^^

SyntaxError: Cannot use import statement outside a module

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
  at Object.<anonymous> (node_modules/jest-preset-angular/setup-jest.js:2:24)

`

@klevismehmeti
Copy link

upgraded to angular 14, and i have this problem: `Details:

/Users/user1/Documents/core-obg-ngx-packages-core/node_modules/@angular/core/fesm2020/testing.mjs:7
import { getDebugNode as getDebugNode$1, RendererFactory2 as RendererFactory2$1, ɵstringify, ɵReflectionCapabilities, Directive, Component, Pipe, NgModule, ɵgetInjectableDef, resolveForwardRef as resolveForwardRef$1, ɵNG_COMP_DEF, ɵRender3NgModuleRef, ApplicationInitStatus, LOCALE_ID as LOCALE_ID$1, ɵ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 as InjectionToken$1, Injector as Injector$1, InjectFlags as InjectFlags$1, ɵsetAllowDuplicateNgModuleIdsForTest, ɵresetCompiledComponents, ɵsetUnknownElementStrictMode as ɵsetUnknownElementStrictMode$1, ɵsetUnknownPropertyStrictMode as ɵsetUnknownPropertyStrictMode$1, ɵgetUnknownElementStrictMode as ɵgetUnknownElementStrictMode$1, ɵgetUnknownPropertyStrictMode as ɵgetUnknownPropertyStrictMode$1, ɵflushModuleScopingQueueAsMuchAsPossible } from '@angular/core';
^^^^^^

SyntaxError: Cannot use import statement outside a module

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1796:14)
  at Object.<anonymous> (node_modules/jest-preset-angular/setup-jest.js:2:24)

`

So apparently my problem happened because of this
Screenshot 2022-08-04 at 10 53 55

@alxpsr
Copy link

alxpsr commented Oct 31, 2022

Only that works for me (ng13 + nx)

transform: {
    '^.+\\.(ts|js|mjs|html)$': 'jest-preset-angular'
},
transformIgnorePatterns: ['<rootDir>/node_modules/'],

So you have to add mjs to transform array and ignore either entire node_modules or just specific libs

@dragosgry89
Copy link

@klevismehmeti how exactly did you manage to fix your issue with node_modules/@angular/core/fesm2020/testing.mjs:7 ?
I am currently facing the exact same issue every time I add transform + transformIgnorePattern in jest config, even something as simple as
transform: { '^.+\\.(ts|js|mjs|html)$': 'jest-preset-angular' }, transformIgnorePatterns: [ '<rootDir>/node_modules/' ],

angular 14
ns 8.4.0

@AndrewCochrane24
Copy link

@klevismehmeti how exactly did you manage to fix your issue with node_modules/@angular/core/fesm2020/testing.mjs:7 ? I am currently facing the exact same issue every time I add transform + transformIgnorePattern in jest config, even something as simple as transform: { '^.+\\.(ts|js|mjs|html)$': 'jest-preset-angular' }, transformIgnorePatterns: [ '<rootDir>/node_modules/' ],

angular 14 ns 8.4.0

I don't know if you're still struggling with this but the same thing was happening for me on Angular 15.0.4. I had to specify each module as they failed the test, like so:

 transform: {
    '^.+\\.(ts|mjs|js|html)$': 'jest-preset-angular',
  },
  transformIgnorePatterns: ['<rootDir>/node_modules/(?!@angular|@ux-aspects|d3|internmap|delaunator|robust-predicates)'],

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.