Jest: SyntaxError: Unexpected token import, testing ES6 typescript components

Created on 13 Aug 2017  ยท  5Comments  ยท  Source: facebook/jest

I've read the docs, read blog posts, read multiple stack posts and i can't find any solution that has worked for me.

 jest --no-cache
 FAIL  __test__\components\stats\stats.components.test.js
  โ— Test suite failed to run
  ...\src\components\stats\stats.component.tsx:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filenam
e,global,jest){import * as React from 'react';
               ^^^^^^
    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (../../../AppData/Roaming/
npm/node_modules/jest/node_modules/jest-runtime/build/ScriptTransformer.js:289
:17)
      at Object.<anonymous> (__test__/components/stats/stats.components.test.j
s:3:13)

Jest docs for example about how to test react components makes it look like testing an ES6 component should just work. But doesn't for me and I have no idea if it's because my files are using typescript or not.

So I would like some help please, seems like a popular issue imo with no reliable solution.

More detail on my code and configs can be found on my stackoverflow post or if you prefer my repo is here

Thanks

Most helpful comment

even with copying your example babel config I get the same Unexpected token import error, there has to be something else that's not right, the answers on SO also do not work for me

All 5 comments

You have your answers on SO already.
Your babel config should rather look like this:

{
  "presets":  [["es2015", { "modules": false }], "react"],
  "env": {
  "test": {
      "presets":[
        "es2015",
         "stage-0",
        "react"],
      "plugins": [
        "transform-es2015-modules-commonjs",
        "dynamic-import-node"
      ]
    }
  }
}

Normally you want babel _not_ to compile imports, because Webpack understands that. But for tests, you need to compile modules to common js (which is the default of "es2015" preset)

even with copying your example babel config I get the same Unexpected token import error, there has to be something else that's not right, the answers on SO also do not work for me

have you tried running jest --no-cache or npm run test -- --no-cache?

Yeah I tried that too, I have seen jest --no-cache mentioned in a few places so pretty much using it every time i make a change. Still end up with the same error though.

I'm having this issue, but jest doesn't accept an array of presets anymore...

Was this page helpful?
0 / 5 - 0 ratings