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

SyntaxError: Unexpected token import #64

Closed
kidd3 opened this issue Aug 15, 2017 · 51 comments
Closed

SyntaxError: Unexpected token import #64

kidd3 opened this issue Aug 15, 2017 · 51 comments

Comments

@kidd3
Copy link

kidd3 commented Aug 15, 2017

I have a similar issue to the one posted in #4, however I have tried the suggested fixes and none of them are resolving the issue for me.

I am importing a package of my own creation into an Angular 2+ project, I can build the project and run it perfectly, but running tests in Jest with Jest-Preset-Angular throws the error:

SyntaxError: Unexpected token import

I've tried adding my package to a whitelist such as:

"transformIgnorePatterns": [
    "node_modules/(?!@ngrx|service-layer)"
] 

And my tsconfig.spec.json file is as follows:

{
"extends": "./tsconfig.es5.json",
"compilerOptions": {
"outDir": "../out-tsc/spec",
"module": "commonjs",
"target": "es6",
"baseUrl": "",
"types": [
"jest",
"node"
],
"allowJs": true
},
"files": [
"**/*.spec.ts"
]
}

Any help would be appreciated

@thymikee
Copy link
Owner

Hard to tell without a repro, or at least more detailed error (with stack trace)

@kidd3
Copy link
Author

kidd3 commented Aug 16, 2017

Sorry, the project I am working on is difficult to share but I will see if I can recreate a repo. The full error i get is:

Test suite failed to run

/Users/user/Documents/App/mainApp/node_modules/service-layer/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { Injectable, NgModule } from '@angular/core';
                                                                                         ^^^^^^
SyntaxError: Unexpected token import
  
  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/ScriptTransformer.js:289:17)
  at Object.<anonymous> (src/request-abstract.service.ts:3:81)
  at Object.<anonymous> (src/services/registration.service.ts:3:87)

@thymikee
Copy link
Owner

Have you tried running jest with --no-cache flag?

@kidd3
Copy link
Author

kidd3 commented Aug 16, 2017

I have tried --no-cache yes, I have a script in my package.json file "test": "jest" and I have run npm run test --no-cache

All the line numbers in the error appear to point to the end of the import statements in those files, so it appears it is unable to import anything from node_modules?

The full section about jest in my package.json file is as follows:

"jest": {
   "preset": "jest-preset-angular",
   "setupTestFrameworkScriptFile": "<rootDir>/src/jest.ts",
   "collectCoverage": true,
   "coverageDirectory": "coverage",
   "collectCoverageFrom": [
     "src/**/*.ts",
     "**/config/**",
     "!src/**/jest.ts"
   ],
   "coverageReporters": [
     "json",
     "lcov"
   ],
   "transformIgnorePatterns": [
     "node_modules/(?!@ngrx|service-layer)"
   ]
},

@thymikee
Copy link
Owner

It should be npm run test -- --no-cache

@kidd3
Copy link
Author

kidd3 commented Aug 16, 2017

Sorry, that is what i meant, just a mistake in my typing.

@kidd3
Copy link
Author

kidd3 commented Aug 16, 2017

All the errors are pointing to lines in files where there are imports, such as: import { Observable } from 'rxjs/Observable'; and {import { NgModule } from "@angular/core";

Am I missing anything that allows Jest to access the node_modules folder? It currently appears like it just can't find it or access it. I am just guessing though.

@thymikee
Copy link
Owner

thymikee commented Aug 16, 2017

By default Jest doesn't transpile code in node_modules, hence the whitelist in transformIgnorePatterns. You can set it to:

   "transformIgnorePatterns": [
     "node_modules"
   ]

if you want to transpile all node_modules (not recommended though). It's advised to add untranspiled node modules to this list, so you'd end up with something like:

   "transformIgnorePatterns": [
     "node_modules/(?!@ngrx|service-layer|@angular/core|rxjs)"
   ]

@kidd3
Copy link
Author

kidd3 commented Aug 16, 2017

Ok that makes sense, so I have now tried with all node_modules as:

"transformIgnorePatterns": [
    "node_modules"
 ]

and the error stays exactly the same (very odd), but changing the list values to be:

"transformIgnorePatterns": [
     "node_modules/(?!rxjs|@angular/core|service-layer)"
]

This now gives me a completely new error:

Test suite failed to run

TypeError: Cannot read property 'type' of undefined
  
  at Object.getEffectiveTypeAnnotationNode (node_modules/typescript/lib/typescript.js:9341:17)
  at assignContextualParameterTypes (node_modules/typescript/lib/typescript.js:41652:25)
  at checkFunctionExpressionOrObjectLiteralMethod (node_modules/typescript/lib/typescript.js:41948:29)
  at checkExpressionWorker (node_modules/typescript/lib/typescript.js:42959:28)
  at checkExpression (node_modules/typescript/lib/typescript.js:42898:42)
  at checkExpressionCached (node_modules/typescript/lib/typescript.js:42779:38)
  at checkReturnStatement (node_modules/typescript/lib/typescript.js:45418:54)
  at checkSourceElement (node_modules/typescript/lib/typescript.js:46763:28)
  at Object.forEach (node_modules/typescript/lib/typescript.js:1506:30)
  at checkBlock (node_modules/typescript/lib/typescript.js:44563:16)

So, following the same pattern, I have added typescript to the whitelist, and then I get yet another error:

[BABEL] Note: The code generator has deoptimised the styling of "/Users/user/Documents/App/mainApp/node_modules/typescript/lib/typescript.js" as it exceeds the max of "500KB".
FAIL  src/services/registration.service.spec.ts
Test suite failed to run

TypeError: require(...).install is not a function
  
  at Object.<anonymous> (node_modules/typescript/lib/typescript.js:1:109)
  at Object.<anonymous> (node_modules/ts-jest/dist/transpile-if-ts.js:3:11)
  at Object.<anonymous> (node_modules/ts-jest/dist/default-retrieve-file-handler.js:4:25)
  at Object.<anonymous> (node_modules/ts-jest/dist/index.js:4:39)
  at Object.<anonymous> (node_modules/ts-jest/index.js:1:107)
  at Object.<anonymous> (src/jest.ts:1:103)
  at process._tickCallback (internal/process/next_tick.js:109:7)

@thymikee
Copy link
Owner

You shouldn't add typescript to whitelist, the error you get is not SyntaxError. Sorry, but no idea right now, what may be the cause right now. You may want to search for this error in ts-jest repo or Stack Overflow

@kidd3
Copy link
Author

kidd3 commented Aug 16, 2017

OK, I have tried to experiment with adding/removing packages from the whitelist, but ultimately now I am stuck on the TypeError: Cannot read property 'type' of undefined error from above. Below is the output from jest --debug if that might give any clues? I will have a look at the ts-jest documentation also as you suggest.

  "config": {
    "automock": false,
    "browser": false,
    "cache": true,
    "cacheDirectory": "/var/folders/m1/2ldjz8q16pj_47rf0wflny_00000gp/T/jest_dy",
    "clearMocks": false,
    "coveragePathIgnorePatterns": [
      "/node_modules/"
    ],
    "globals": {
      "ts-jest": {
        "tsConfigFile": "src/tsconfig.spec.json"
      },
      "__TRANSFORM_HTML__": true
    },
    "haste": {
      "providesModuleNodeModules": []
    },
    "moduleDirectories": [
      "node_modules"
    ],
    "moduleFileExtensions": [
      "ts",
      "js",
      "html",
      "json"
    ],
    "moduleNameMapper": [
      [
        "(.*)",
        "/Users/user/Documents/App/mainApp/src/$1"
      ]
    ],
    "modulePathIgnorePatterns": [],
    "name": "18f45d41d4d1a164d661de3adf12f175",
    "resetMocks": false,
    "resetModules": false,
    "rootDir": "/Users/user/Documents/App/mainApp",
    "roots": [
      "/Users/user/Documents/App/mainApp"
    ],
    "setupFiles": [],
    "setupTestFrameworkScriptFile": "/Users/user/Documents/App/mainApp/src/jest.ts",
    "snapshotSerializers": [],
    "testEnvironment": "jest-environment-jsdom",
    "testMatch": [],
    "testPathIgnorePatterns": [
      "/node_modules/"
    ],
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|js)$",
    "testRunner": "/Users/user/Documents/App/mainApp/node_modules/jest-jasmine2/build/index.js",
    "testURL": "about:blank",
    "timers": "real",
    "transform": [
      [
        "^.+\\.(ts|js|html)$",
        "/Users/user/Documents/App/mainApp/node_modules/jest-preset-angular/preprocessor.js"
      ]
    ],
    "transformIgnorePatterns": [
      "/Users/user/Documents/App/mainApp/node_modules/(?!rxjs/Rx|rxjs/Observable|rxjs/observable|@angular/core|@angular/http|@angular/common|@angular/compiler/@angular|@angular/platform-browser-dynamic|@angular/platform-browser/bundles|service-layer)"
    ]
  },
  "framework": "jasmine2",
  "globalConfig": {
    "bail": false,
    "collectCoverage": true,
    "collectCoverageFrom": [
      "src/**/*.ts",
      "!**/config/**",
      "!src/**/jest.ts"
    ],
    "coverageDirectory": "/Users/user/Documents/App/mainApp/coverage",
    "coverageReporters": [
      "json",
      "lcov"
    ],
    "expand": false,
    "mapCoverage": true,
    "noStackTrace": false,
    "notify": false,
    "projects": [
      "/Users/user/Documents/App/mainApp"
    ],
    "rootDir": "/Users/user/Documents/App/mainApp",
    "testPathPattern": "",
    "testResultsProcessor": null,
    "updateSnapshot": "new",
    "useStderr": false,
    "verbose": null,
    "watch": false,
    "watchman": true
  },
  "version": "20.0.4"
}

@thymikee
Copy link
Owner

@kidd3 can you check the discussion in #66 and see if it helps?

@kidd3
Copy link
Author

kidd3 commented Aug 25, 2017

@thymikee I have tried the suggested solution in #66 and unfortunately I am still getting the same Unexpected token error. It only happens when I am importing a package in the .spec file and attempt to use something from that package. The package is very very basic at the moment, and is a package I created myself.
I will try and create a stripped down example repo to illustrate the problem I am having.

@kidd3
Copy link
Author

kidd3 commented Aug 25, 2017

I've made a demo repo where the error is occurring: https://github.com/kidd3/SL
Clone, npm install, and then npm run test will throw the error.
My separate demo package which gets installed and referenced is called "jest-test", this just contains some very basic number functions as examples. Commenting out the references to this package and the 'SampleService' causes the test to succeed.

@thymikee
Copy link
Owner

Thanks, I'll get to it when I have some free time, because I'm pretty busy at the moment :<

@sharikovvladislav
Copy link
Contributor

What is your babel config?

Also what is your jest config?

Actulally you don't need babel. Jest already have babel-jest out of the box. You can use it. Why you use babel?

@kidd3
Copy link
Author

kidd3 commented Aug 25, 2017

Thanks @thymikee, I appreciate it, sorry you are busy.

@sharikovvladislav I wasn't using babel, however I was attempting to see if the fix suggested on #66 to use a .babelrc file and updating my jest config inside the package.json file to include:
"useBabelrc": true
There is a very good chance I have missed some steps to that solution?

@sharikovvladislav
Copy link
Contributor

sharikovvladislav commented Aug 25, 2017

Can you show your jest config?

We can try to solve your problem as my was sovled. If it is not similar, I don't think I can help :( So lets see.

@kidd3
Copy link
Author

kidd3 commented Aug 25, 2017

Running jest --debug gives me this:

"config": {
"automock": false,
"browser": false,
"cache": true,
"cacheDirectory": "/var/folders/m1/2ldjz8q16pj_47rf0wflny_00000gp/T/jest_dy",
"clearMocks": false,
"coveragePathIgnorePatterns": [
"/node_modules/"
],
"globals": {
"ts-jest": {
"tsConfigFile": "src/tsconfig.spec.json",
"useBabelrc": true
},
"__TRANSFORM_HTML__": true
},
"haste": {
"providesModuleNodeModules": []
},
"moduleDirectories": [
"node_modules"
],
"moduleFileExtensions": [
"ts",
"js",
"html",
"json"
],
"moduleNameMapper": [
[
"(.*)",
"/Users/user/Documents/Jest test/SL/src/$1"
]
],
"modulePathIgnorePatterns": [],
"name": "103c4477a9d570aceb8e4bc5aa20e7ac",
"resetMocks": false,
"resetModules": false,
"rootDir": "/Users/user/Documents/Jest test/SL",
"roots": [
"/Users/user/Documents/Jest test/SL"
],
"setupFiles": [
"/Users/user/Documents/Jest test/SL/node_modules/regenerator-runtime/runtime.js"
],
"setupTestFrameworkScriptFile": "/Users/user/Documents/Jest test/SL/src/jest.ts",
"snapshotSerializers": [],
"testEnvironment": "jest-environment-jsdom",
"testMatch": [],
"testPathIgnorePatterns": [
"/node_modules/"
],
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|js)$",
"testRunner": "/Users/user/Documents/Jest test/SL/node_modules/jest-jasmine2/build/index.js",
"testURL": "about:blank",
"timers": "real",
"transform": [
[
"^.+\\.(ts|html)$",
"/Users/user/Documents/Jest test/SL/node_modules/jest-preset-angular/preprocessor.js"
],
[
"^.+\\.js$",
"/Users/user/Documents/Jest test/SL/node_modules/babel-jest/build/index.js"
]
],
"transformIgnorePatterns": [
"node_modules/(?!jest-test)"
]
},
"framework": "jasmine2",
"globalConfig": {
"bail": false,
"collectCoverage": true,
"collectCoverageFrom": [
"src/**/*.ts",
"!**/node_modules/**",
"!**/config/**",
"!src/**/jest.ts"
],
"coverageDirectory": "/Users/user/Documents/Jest test/SL/coverage",
"coverageReporters": [
"json",
"lcov"
],
"expand": false,
"mapCoverage": true,
"noStackTrace": false,
"notify": false,
"projects": [
"/Users/user/Documents/Jest test/SL"
],
"rootDir": "/Users/user/Documents/Jest test/SL",
"testPathPattern": "",
"testResultsProcessor": null,
"updateSnapshot": "new",
"useStderr": false,
"verbose": null,
"watch": false,
"watchman": true
},
"version": "20.0.4"
}

@kidd3
Copy link
Author

kidd3 commented Aug 25, 2017

Thanks @sharikovvladislav, is the above information what you need?

@sharikovvladislav
Copy link
Contributor

Can you provide full output where you see the error?

@kidd3
Copy link
Author

kidd3 commented Aug 25, 2017

Sure, the error is:

 Test suite failed to run

/Users/user/Documents/Jest test/SL/node_modules/jest-test/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { Component, Injectable, NgModule } from '@angular/core';
^^^^^^
SyntaxError: Unexpected token import

at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/ScriptTransformer.js:289:17)
at Object.<anonymous> (src/services/register.service.spec.ts:3:17)

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

@kidd3
Copy link
Author

kidd3 commented Aug 25, 2017

I have a demo repo here as well if it is helpful, as it has the error occurring: https://github.com/kidd3/SL
Clone, npm install, and then npm run test will throw the error.

@sharikovvladislav
Copy link
Contributor

@kidd3 ok sry my bad. I forget. Yes you need .babelrc for setting preset.

Here is config:

  "jest": {
    "preset": "jest-preset-angular",
    "setupTestFrameworkScriptFile": "<rootDir>/src/jest.ts",
    "transform": {
      "^.+\\.(ts|html)$": "<rootDir>/node_modules/jest-preset-angular/preprocessor.js",
      "^.+\\.js$": "babel-jest"
    },
    "transformIgnorePatterns": [
      "node_modules/(?!(jest-test))"
    ],
    "globals": {
      "ts-jest": {
        "tsConfigFile": "src/tsconfig.spec.json",
        "useBabelrc": true
      },
      "__TRANSFORM_HTML__": true
    }
  },

and here is babelrc contents:

{
    "presets": ["env"]
}

@sharikovvladislav
Copy link
Contributor

Here is PR. It solves the problem: https://github.com/kidd3/SL/pull/4

@sharikovvladislav
Copy link
Contributor

I also pushed coverage, accidently removed it.

@kidd3
Copy link
Author

kidd3 commented Aug 25, 2017

@sharikovvladislav the only thing I can see that has changed is:

"transformIgnorePatterns": [
      "node_modules/(?!jest-test)"
    ]

becomes:

"transformIgnorePatterns": [
      "node_modules/(?!(jest-test))"
    ]

For me this 1 change of adding the extra brackets isn't fixing the issue, did I miss something?

@sharikovvladislav
Copy link
Contributor

sharikovvladislav commented Aug 25, 2017

Nope. Main is adding .babelrc. http://prntscr.com/gcxyu4

@kidd3
Copy link
Author

kidd3 commented Aug 25, 2017

ah damn, I'm a fool! I had a .babelrc file but I had put it inside the /src folder when it needed to be in the root folder! Thank you @sharikovvladislav for your fresh eyes to see this and find it, I appreciate it very much!

@sharikovvladislav
Copy link
Contributor

sharikovvladislav commented Aug 25, 2017

Nope. Thank you to @DorianGrey. He perfectly explained everything there: #66 (comment)

@DorianGrey
Copy link

Be sure that I figured it out the hard way ;)
I've evaluated the usage of jest a while ago in my angular template and faced a similar problem with lodash-es:
DorianGrey/ng-webpack-template@dce61c9

Technically, it should be sufficient to just use a babel config like this:

{
   "plugins": [
     "transform-es2015-modules-commonjs"
   ]
 }

This is included in the env preset, in addition to several other plugins and a basic config that can deal with way more cases than the "simple" one I've had with lodash-es, which is why I suggested it in favor of the single plugin version.

@moneydance
Copy link

Why is babel necessary, shouldn't the tsc be able to compile to es5? There is no mention of it in the docs.

@sharikovvladislav
Copy link
Contributor

@moneydance it turns out that tsc does not compile to es5 some of files.

We already realized that with @thymikee and I am going to make a PR to fix this.

@thymikee it turns out that we should change not only docs, but config generated by preset, shouldn't we?

@sharikovvladislav
Copy link
Contributor

sharikovvladislav commented Aug 25, 2017

I mean this one should be separated to 2 lines: for ts/html & js. We should mention this in docs and also we should say about .babelrc. What do you think @thymikee ?

@moneydance
Copy link

Hey thanks for the quick response! Okay I will try adding .babelrc and see if it fixes my issues.

@thymikee
Copy link
Owner

@sharikovvladislav yea, that's probably a right thing to do, because compiling js through tsc is kind of hacky anyway. However I'm thinking if we should keep the config how it is, and put some information about it in troubleshooting guide.

@thymikee
Copy link
Owner

Closing this issue, but let's keep the discussion going

@kirillgroshkov
Copy link

Also having same issue

@FezVrasta
Copy link

I'm having the same problem and the steps described didn't help

@thymikee
Copy link
Owner

Hard to help without any repro. I guess, you already checked this one #66 (comment)?

@FezVrasta
Copy link

Yup... I get TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string 🤷‍♀️

@thymikee
Copy link
Owner

Try to narrow it down to simples case and go from there. This error tells me nothing unfortunately.

@DamengRandom
Copy link

None of this works of angular 6 ... Is there any proper solution for angular 6?

@ahnpnl
Copy link
Collaborator

ahnpnl commented Aug 16, 2018

@DamengRandom what is your test setup and what are the test cases which produce the error ?

@mo-norant
Copy link

Still the same problem here

@wtho
Copy link
Collaborator

wtho commented Dec 15, 2018

@mo-norant if you could provide a reproduction, preferably with a minimal project, we can look into it.

@ahnpnl
Copy link
Collaborator

ahnpnl commented Dec 15, 2018

Hi @mo-norant , this issue has been answered in #185 . It is related to your tsconfig.spec.json. You need to add module: commonjs and then run jest --clearCache. After that you can run your test again.

We also have an example app with base configuration in our example folder or you can take a look at my sample repo at https://github.com/ahnpnl/jest-angular

@maxime1992
Copy link
Contributor

If anyone come across that error take a look into the PR above ☝️

@lipalath-ms
Copy link

lipalath-ms commented Apr 9, 2019

I upgraded office-ui-fabric-react package from 5.124.0 to 6.164.0 and my tests are failing with the following error:

● Test suite failed to run

C:\Users\lp\_\EUS-Col\PA\node_modules\office-ui-fabric-react\lib\DetailsList.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export * from './components/DetailsList/index';
                                                                                         ^^^^^^

SyntaxError: Unexpected token export
  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/ScriptTransformer.js:289:17)
  at Object.<anonymous> (src/webparts/publishApps/Components/LS/LSComponent.tsx:17:73)
  at Object.<anonymous> (src/webparts/publishApps/Components/LS/tests/RS.test.tsx:18:34)

Please see the package.json file below:

package.txt

Can anyone please help me to resolve this?

@wtho
Copy link
Collaborator

wtho commented Apr 11, 2019

@xyz92 I don't think you should test a react-library with an Angular Jest preset.

Seems like your transformer does not like es6, make sure you set es5 as compilation target for TyepScript.

@ahnpnl
Copy link
Collaborator

ahnpnl commented Apr 11, 2019

in addition, regarding to test react-library with typescript and jest, please refer to ts-jest

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

No branches or pull requests