angular-builders icon indicating copy to clipboard operation
angular-builders copied to clipboard

Cannot run tests when having `import.meta.url`

Open monkeycon opened this issue 5 years ago • 15 comments

Describe the Bug

Jest cannot compile when there is import.meta.url in the code, even in console.log.

The use of import.meta.url is obligatory in Angular 12 for new Worker(new URL('./app.worker', import.meta.url), ...)

https://angular.io/guide/updating-to-version-12#breaking-changes-in-angular-version-12 Angular 12 updates Webpack from version 4 to version 5.

  • Webpack 5 now includes web worker support. However, the structure of the URL within the worker constructor must be in a specific format that differs from the current requirement. To update web worker usage, where ./app.worker is the actual worker name, change new Worker('./app.worker', ...) to new Worker(new URL('./app.worker', import.meta.url), ...). See PR #20466.
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  title = 'my-app';

  ngOnChanges(): void {
    console.log(import.meta.url);
  }
}
$ ng test
 FAIL  src/app/app.component.spec.ts
  ● Test suite failed to run

    src/app/app.component.ts:17:17 - error TS1343: The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'esnext', or 'system'.

    17     console.log(import.meta.url);
                       ~~~~~~~~~~~

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        3.464 s
Ran all test suites.
error Command failed with exit code 1.

tsconfig.json: generated by Angular 12

{
  ...
  "compilerOptions": {
    ...
    "module": "es2020",
  },
  ...
}

Minimal Reproduction

Create a new app ng new my-app; Follow the guide https://www.npmjs.com/package/@angular-builders/jest to add @angular-builders/jest; Add import.meta.url in the code (wherever); Run the tests.

Expected Behavior

Run the tests successfully.

Screenshots

image

Environment

Libs

  • @angular/core version: "~12.0.1"
  • @angular-devkit/build-angular version: "~12.0.1"
  • @angular-builders/jest version: "^12.1.0"

For Tooling issues:

  • Node version: v14.16.1
  • Platform: Windows 10

monkeycon avatar Jun 17 '21 08:06 monkeycon

Hey. What's the module config in your tsconfig.spec.json?

just-jeb avatar Jun 22 '21 06:06 just-jeb

Hi I add es2020

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    ...
    "module": "es2020",
  },
  ...
}

monkeycon avatar Jun 22 '21 14:06 monkeycon

Seems like you have to specify in jest config that you want to use ESM features.
It is debatable whether it should be part of the builder or not, we can talk about it.
But first let's check if it solves your issue.

just-jeb avatar Jun 27 '21 11:06 just-jeb

Hi! I'm facing the same problem. I'd like to use import.meta.url in my app but it will make the tests fail and I'm not being able to make it work or find any workaround so that Jest can skip that part somehow...

I made a minimal repro to isolate the problem: https://github.com/acalvo/import-meta-url . This is the commit with all the changes: https://github.com/acalvo/import-meta-url/commit/1086a14241ccaf39d82276bfa9d9308ac383e647

ng test fails with the same error as the OP 😔. Any clues of what's missing or how could make it work?

Thanks!!

acalvo avatar Jul 01 '21 11:07 acalvo

Hey @acalvo, have you tried this?

just-jeb avatar Jul 05 '21 07:07 just-jeb

Hi @just-jeb ! You mean this, don't you? https://github.com/acalvo/import-meta-url/blob/master/jest.config.js#L2

I used the preset as you see (instead of the manual config). Makes no difference... :/

acalvo avatar Jul 05 '21 07:07 acalvo

@acalvo actually I meant the manual configuration (since it adds it on top of angular-jest-preset that is used by the builder).

just-jeb avatar Jul 11 '21 11:07 just-jeb

@just-jeb I just uploaded a branch (feature/manual-config) to change the preset with the manual config as stated in the docs: https://github.com/acalvo/import-meta-url/blob/feature/manual-config/jest.config.js

And I'm getting the same error...

Screenshot 2021-07-12 at 10 12 12

Module is es2020 though: https://github.com/acalvo/import-meta-url/blob/feature/manual-config/tsconfig.spec.json#L5

Not sure if anyone (OP @monkeycon ?) could make it work somehow. Thanks for the help!

acalvo avatar Jul 12 '21 08:07 acalvo

Hello @acalvo. Here is the fix to your minimal reproduction that will allow you to use import.meta.url:

diff --git a/jest.config.js b/jest.config.js
index 7c11975..40e59f4 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -1,8 +1,3 @@
 module.exports = {
-    "preset": "jest-preset-angular/presets/defaults-esm",
-    "globals": {
-        "ts-jest": {
-            "tsconfig": "<rootDir>/tsconfig.spec.json"
-        }
-    }
+  "preset": "jest-preset-angular/presets/defaults-esm",
 };
diff --git a/package.json b/package.json
index 3fd50b0..ce8124d 100644
--- a/package.json
+++ b/package.json
@@ -6,7 +6,7 @@
     "start": "ng serve",
     "build": "ng build",
     "watch": "ng build --watch --configuration development",
-    "test": "ng test"
+    "test": "NODE_OPTIONS=--experimental-vm-modules ng test"
   },
   "private": true,
   "dependencies": {
diff --git a/tsconfig.spec.json b/tsconfig.spec.json
index 70dfb05..e29984c 100644
--- a/tsconfig.spec.json
+++ b/tsconfig.spec.json
@@ -6,6 +6,7 @@
     "target": "es5",
     "esModuleInterop": true,
     "allowJs": true,
+    "allowSyntheticDefaultImports": true,
     "types": [
       "jest",
       "node"

It might be worth encapsulating it inside the builder (certainly the preset part) but it shouldn't block you.

just-jeb avatar Jul 19 '21 09:07 just-jeb

Great, it works! I had already run it with the NODE_OPTIONS=--experimental-vm-modules flag, but discarded it due to the errors it produced. But they're gone with the TS allowSyntheticDefaultImports flag. Thank you for your help! 😄

acalvo avatar Jul 19 '21 14:07 acalvo

@monkeycon Is your issue resolved? I am still facing same issue.

Avinash4243 avatar Feb 22 '22 08:02 Avinash4243

Great, it works! I had already run it with the NODE_OPTIONS=--experimental-vm-modules flag, but discarded it due to the errors it produced. But they're gone with the TS allowSyntheticDefaultImports flag. Thank you for your help! 😄

Can you please help me fix the same issue for me. I am still facing the same issue.

Hey! See the minimal reproduction I linked above: https://github.com/acalvo/import-meta-url

And apply the git diff just-jeb gave me. With those changes, it won't throw any errors.

acalvo avatar Feb 22 '22 12:02 acalvo

Great, it works! I had already run it with the NODE_OPTIONS=--experimental-vm-modules flag, but discarded it due to the errors it produced. But they're gone with the TS allowSyntheticDefaultImports flag. Thank you for your help! 😄

Can you please help me fix the same issue for me. I am still facing the same issue.

Hey! See the minimal reproduction I linked above: https://github.com/acalvo/import-meta-url

And apply the git diff just-jeb gave me. With those changes, it won't throw any errors.

Thank you for the reply - Do I need to add @angular-builders/jest dependency also in my project or it is not required. I added and checked also followed the diff changes still getting the same issue.

Avinash4243 avatar Feb 23 '22 03:02 Avinash4243

Hi @acalvo are your configurations + diff changes applied from just-jeb still working for this error? I'm using @angular-builders/jest 17.0.3, and tried your config with diffs applied and the below error is thrown(a different one). Maybe I'm missing something. @Avinash4243 did you managed to fix it for your case ?

Thank you in advance!

error:

 ● 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
    
    SyntaxError: Cannot use import statement outside a module

jest.config.js:

module.exports = {
  preset: "jest-preset-angular/presets/defaults-esm",
};

ts.config.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "strict": true,
    "noImplicitOverride": true,
    "noPropertyAccessFromIndexSignature": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "sourceMap": true,
    "declaration": false,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "ES2022",
    "module": "ES2022",
    "useDefineForClassFields": false,
    "types": ["jest", "node"],
    "lib": ["ES2022", "dom"]
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}

tsconfig.spec.json:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/spec",
    "target": "ES2022",
    "module": "ES2022",
    "esModuleInterop": true,
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "types": ["jest", "node"]
  },
  "include": ["src/**/*.spec.ts", "src/**/*.d.ts"]
}

angular.json architect.test config:

        "test": {
          "builder": "@angular-builders/jest:run",
          "options": {
            "tsConfig": "tsconfig.spec.json",
            "polyfills": ["zone.js", "zone.js/testing"]
        }

package.json scripts:

  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "NODE_OPTIONS=--experimental-vm-modules ng test"
  }

vitaliecirjeleanu avatar May 12 '24 14:05 vitaliecirjeleanu

@vitaliecirjeleanu Hi, did you manage to resolve the issue ?

Oneia avatar Dec 10 '24 16:12 Oneia