question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. ItĀ collects links to all the places you might be looking at while hunting down a tough bug.

And, if youā€™re still stuck at the end, weā€™re happy to hop on a call to see how we can help out.

Jest encountered unexpected token with React app

See original GitHub issue

šŸ› Bug Report

When trying to run tests with Jest in a React app, I get a Jest encountered an unexpected token error. I copied the Link component and test directly from here. This is the error:

FAIL  src/components/Link.test.js
  ā— Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     ā€¢ 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/en/configuration.html

    Details:

    SyntaxError: C:\workspace\react\testapp\src\components\Link.test.js: Unexpected token (8:4)

       6 | test('Link changes the class when hovered', () => {
       7 |   const component = renderer.create(
    >  8 |     <Link page="http://www.facebook.com">Facebook</Link>,
         |     ^
       9 |   );
      10 |   let tree = component.toJSON();
      11 |   expect(tree).toMatchSnapshot();

      at Parser.raise (node_modules/@babel/parser/lib/index.js:3938:15)
      at Parser.unexpected (node_modules/@babel/parser/lib/index.js:5247:16)
      at Parser.parseExprAtom (node_modules/@babel/parser/lib/index.js:6327:20)
      at Parser.parseExprSubscripts (node_modules/@babel/parser/lib/index.js:5923:21)
      at Parser.parseMaybeUnary (node_modules/@babel/parser/lib/index.js:5902:21)
      at Parser.parseExprOps (node_modules/@babel/parser/lib/index.js:5811:21)
      at Parser.parseMaybeConditional (node_modules/@babel/parser/lib/index.js:5783:21)
      at Parser.parseMaybeAssign (node_modules/@babel/parser/lib/index.js:5730:21)
      at Parser.parseExprListItem (node_modules/@babel/parser/lib/index.js:6994:18)
      at Parser.parseCallExpressionArguments (node_modules/@babel/parser/lib/index.js:6123:22)

Hereā€™s my package.json

{
  "name": "testapp",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "start": "webpack-dev-server --config ./config/webpack.config.development.js",
    "build": "webpack -p --config ./config/webpack.config.production.js",
    "test": "jest"
  },
  "dependencies": {
    "axios": "^0.18.0",
    "moment": "^2.22.2",
    "polished": "^2.0.3",
    "prop-types": "^15.6.2",
    "react": "^16.4.2",
    "react-delay-render": "^0.1.2",
    "react-dom": "^16.4.2",
    "react-imported-component": "^4.6.2",
    "react-router-dom": "^4.3.1",
    "simple-grid": "^1.0.1",
    "styled-components": "^3.4.5",
    "uuid": "^3.3.2",
    "validator": "^10.7.0"
  },
  "devDependencies": {
    "@babel/core": "^7.0.0",
    "@babel/plugin-proposal-class-properties": "^7.0.0",
    "@babel/plugin-syntax-dynamic-import": "^7.0.0",
    "@babel/preset-env": "^7.0.0",
    "@babel/preset-react": "^7.0.0",
    "babel-core": "7.0.0-bridge.0",
    "babel-jest": "^23.4.2",
    "babel-loader": "^8.0.0",
    "babel-plugin-styled-components": "^1.6.0",
    "css-loader": "^1.0.0",
    "html-webpack-plugin": "^3.2.0",
    "jest": "^23.5.0",
    "mini-css-extract-plugin": "^0.4.2",
    "react-test-renderer": "^16.4.2",
    "regenerator-runtime": "^0.12.1",
    "style-loader": "^0.23.0",
    "webpack": "^4.17.1",
    "webpack-cli": "^3.1.0",
    "webpack-dev-server": "^3.1.7"
  }
}

Hereā€™s my .babelrc file (located in the root directory):

{
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "babel-plugin-styled-components",
    "@babel/plugin-syntax-dynamic-import"
  ],
  "presets": ["@babel/preset-env", "@babel/preset-react"],
  "env": {
    "development": {
      "plugins": [
        "@babel/plugin-proposal-class-properties",
        ["babel-plugin-styled-components", { "displayName": true }],
        "@babel/plugin-syntax-dynamic-import"
      ],
      "presets": ["@babel/preset-env", "@babel/preset-react"]
    },
    "test": {
      "plugins": [
        "@babel/plugin-proposal-class-properties",
        ["babel-plugin-styled-components", { "displayName": true }],
        "@babel/plugin-syntax-dynamic-import"
      ],
      "presets": ["@babel/preset-env", "@babel/preset-react"]
    },
    "production": {
      "plugins": [
        "@babel/plugin-proposal-class-properties",
        "babel-plugin-styled-components",
        "@babel/plugin-syntax-dynamic-import"
      ],
      "presets": ["@babel/preset-env", "@babel/preset-react"]
    }
  }
}

To Reproduce

Steps to reproduce the behavior:

  • Install Jest with yarn add --dev babel-jest babel-core@^7.0.0-0 @babel/core
  • Create a test
  • Run yarn test

Expected behavior

  • Jest should work

Run npx envinfo --preset jest

Paste the results here:

OS: Windows 10
    CPU: x64 Intel(R) Xeon(R) CPU E3-1505M v6 @ 3.00GHz
  Binaries:
    Yarn: 1.5.1 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
    npm: 5.6.0 - C:\Program Files\nodejs\npm.CMD

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:162
  • Comments:45

github_iconTop GitHub Comments

124reactions
hoaiduyitcommented, Sep 7, 2018

I have the same problem too.

87reactions
hoaiduyitcommented, Sep 10, 2018

After 3 days, I just find out the solutions for this issue. There are 2 solutions for this:

Solution 1:

You can change your file name from .babelrc to babel.config.js, and this will work.

Solution 2:

Iā€™m using this way. Create a transform file like this (mine is jest-transforme.js):

const config = {
  babelrc: false,
  presets: [
    [
      "@babel/env",
      {
        modules: false
      }
    ],
    "@babel/react"
  ],
  plugins: [
    ["@babel/plugin-proposal-decorators", { legacy: true }],
    ["@babel/plugin-proposal-class-properties", { loose: true }],
    "transform-es2015-modules-commonjs"
  ]
};
module.exports = require("babel-jest").createTransformer(config);

Hereā€™s my jest.config.js:

module.exports = {
  collectCoverageFrom: ["src/**/*.{js,jsx,mjs}"],
  testMatch: ["<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}", "<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"],
  transform: {
    "^.+\\.(js|jsx|mjs)$": "<rootDir>/config/jest/jest-transformer.js"
  },
  transformIgnorePatterns: ["[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$"]
};

And my I still have my .babelrc

const enviroments = require("./env-config.js");

module.exports = {
  presets: [
    [
      "next/babel",
      {
        "preset-env": {
          useBuiltIns: "entry"
        }
      }
    ]
  ],
  plugins: [
    ["styled-components", { ssr: true, displayName: true, preprocess: false }],
    [
      "module-resolver",
      {
        root: ["./"]
      }
    ]
  ],
  env: {
    dev: {
      plugins: [
        ["transform-define", enviroments],
        ["module-resolver", { root: ["./"] }],
        "transform-decorators-legacy",
        "transform-class-properties"
      ]
    },
    build: {
      plugins: [
        ["transform-define", enviroments],
        ["module-resolver", { root: ["./"] }],
        "transform-decorators-legacy",
        "transform-class-properties"
      ]
    },
    production: {
      presets: [
        [
          "minify", // why add minify here, we run uglify over the whole code bundles
          {
            mangle: false,
            evaluate: false
          }
        ]
      ],
      plugins: [
        ["transform-define", enviroments],
        ["@babel/plugin-proposal-decorators", { legacy: true }],
        ["@babel/plugin-proposal-class-properties", { loose: true }],
        ["module-resolver", { root: ["./"] }]
      ],
      comments: false,
      compact: true,
      minified: true
    }
  }
};

Hope this can have you guys pass this issue. Cheer.

Read more comments on GitHub >

github_iconTop Results From Across the Web

create-react-app jest encountered unexpected token
It's because of de ES6 syntax in a package into node_modules, you need to config the "transformIgnorePatterns" to transform this package. TheĀ ...
Read more >
Fix "Jest encountered an unexpected token" with "create-react ...
Here are a few ways I have seen, assume the package is being used @fullcalendar : Use a customized package react app customize-cra...
Read more >
test suite failed to run jest encountered an unexpected token ...
Jest encountered an unexpected token This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not...
Read more >
create-react-app jest encountered unexpected token {-babel.js
[Solved]-create-react-app jest encountered unexpected token {-babel.js ... It's because of de ES6 syntax in a package into node_modules, you need to config the...
Read more >
SyntaxError: Unexpected token when using react-script test
These options in your package.json Jest configuration are not currently supported by Create React App: ā€¢ transformIgnorePatterns If you wish toĀ ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found