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

Jest encountered unexpected token with React app #6933

Closed
mikedloss opened this issue Aug 31, 2018 · 45 comments
Closed

Jest encountered unexpected token with React app #6933

mikedloss opened this issue Aug 31, 2018 · 45 comments

Comments

@mikedloss
Copy link

πŸ› 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
@hoaiduyit
Copy link

I have the same problem too.

@GeorgianSorinMaxim
Copy link

Same problem here.

@fabioSalimbeni
Copy link

same problem here.. slightly more complicated as I'm working with a monorepo.

@GeorgianSorinMaxim
Copy link

@fabioSalimbeni @hoaiduyit @mikedloss I've made my React and React Native tests (Jest and enzyme) pass in a Lerna monorepo using Babel 7.

You need to use the new Babel configuration with babel.config.js if you're working into a monorepo: https://babeljs.io/docs/en/v7-migration.

This is my babel.config.js for the root of the monorepo:

module.exports = {
    overrides: [
        {
            test: 'platforms/webApp1',
            extends: 'platforms/webApp1/babel.config.js'
        },
        {
            test: 'platforms/webApp2',
            extends: 'platforms/webApp2/babel.config.js'
        }
    ]
};

This is how my babel.config.js looks like for webApp1 one of the monorepo apps:

module.exports = {
    env: {
        test: {
            presets: [
                [
                    '@babel/preset-env',
                    {
                        modules: 'commonjs',
                        debug: false
                    }
                ],
                '@babel/preset-flow',
                '@babel/preset-react'
            ],
            plugins: [
                '@babel/plugin-syntax-dynamic-import',
                '@babel/plugin-proposal-class-properties'
            ]
        },
        production: {
            presets: [
                ['@babel/preset-env', { modules: false }],
                '@babel/preset-flow',
                '@babel/preset-react'
            ],
            plugins: [
                '@babel/plugin-syntax-dynamic-import',
                '@babel/plugin-proposal-class-properties'
            ]
        },
        development: {
            presets: [
                ['@babel/preset-env', { modules: false }],
                '@babel/preset-flow',
                '@babel/preset-react'
            ],
            plugins: [
                '@babel/plugin-syntax-dynamic-import',
                '@babel/plugin-proposal-class-properties'
            ]
        }
    }
};

And this is the Jest configuration:

    "jest": {
        "verbose": true,
        "clearMocks": true,
        "collectCoverage": true,
        "setupTestFrameworkScriptFile": "<rootDir>/config/setupTest.js",
        "transform": {
            "^.+\\.js$": "babel-jest"
        },
        "moduleNameMapper": {
            "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
            "\\.(css|scss)$": "<rootDir>/__mocks__/styleMock.js"
        }
    }

setupTest.js looks like:

const Enzyme = require('enzyme');
const Adapter = require('enzyme-adapter-react-16');

Enzyme.configure({ adapter: new Adapter() });

fileMocks.js looks like:

module.exports = 'i-am-a-stubbed-file';

styleMocks.js looks like:

module.exports = {};

You'll also need to add some Babel plugins and the babel-core version as devDependencies in the package.json of each app:

        ...
        "@babel/cli": "^7.0.0",
        "@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-flow": "^7.0.0",
        "@babel/preset-react": "^7.0.0",
        "babel-core": "7.0.0-bridge.0",
        "babel-eslint": "^9.0.0",
        "babel-jest": "^23.4.2",
        "babel-loader": "^8.0.2",
        ...
        "jest": "^23.5.0",
        "jest-cli": "^23.5.0",
        ...
      

@hoaiduyit
Copy link

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.

@hoaiduyit
Copy link

@GeorgianSorinMaxim The problem is my jest app ignore .babelrc file, and change to babel.config.js will solve the problem, but I solved it anyway, my answer is above of this comment.

@fabioSalimbeni
Copy link

thanks @GeorgianSorinMaxim @hoaiduyit in the end I've solved it simply by creating a custom transformer for babel-jest. No other changes where needed.

@SimenB
Copy link
Member

SimenB commented Sep 15, 2018

Babel 7 seems to require babel.config.js to work properly, use that instead of babelrc

@SimenB SimenB closed this as completed Sep 15, 2018
@joselcc
Copy link

joselcc commented Oct 9, 2018

babel-jest still relies in babel-core from Babel 6, if you want to use Babel 7 you can use
this tranformer babel7-jest

@SimenB
Copy link
Member

SimenB commented Oct 9, 2018

babel-jest works just fine with babel 7, no need for a custom transformer

@alexindigo
Copy link

@SimenB I renamed my .babelrc to babel.config.js but it still shows that error with unexpected token. It works with babel7-pre.42 though. Are there any other commonly missed things? :) Thanks.

@20BBrown14
Copy link

@alexindigo Check this out on how to write babel.config.js

https://babeljs.io/docs/en/configuration

@alexindigo
Copy link

Yeah, running yarn upgrade --latest fixed the issue :)

@matthewharwood
Copy link

@alexindigo @hoaiduyit How in the world did you all figure this out about the babel.config.js? Battling the same problem and finding your solutions, I was thinking to myself... "hmmm, Theres no way this is gonna work but I'll try anyway." but sure enough it did lulz. thanks

@anupammaurya
Copy link

Jest & enzyme configuration : Add following code in package.json


"jest": {
    "testEnvironment": "jsdom",
    "moduleDirectories": [
      "src",
      "node_modules"
    ],
    "moduleNameMapper": {
      "\\.(css|scss)$": "<rootDir>/__mocks__/styleMock.js",
      "\\.(jpg|gif|ttf|eot|svg)$": "<rootDir>/__mocks__/fileMock.js"
    },
    "transform": {
      "^.+\\.(js|jsx)$": "babel-jest",
      ".+\\.(css|styl|less|sass|scss)$": "<rootDir>/node_modules/jest-css-modules-transform"
    },
    "setupTestFrameworkScriptFile": "<rootDir>/setupTests.js",
    "setupFiles": [
      "<rootDir>setup.js"
    ],
    "moduleFileExtensions": [
      "css",
      "scss",
      "js",
      "json",
      "jsx"
    ],
    "testRegex": "\/test\/spec\/.*\\.js$",
    "transformIgnorePatterns": [
      "/node_modules/(?!test-component).+\\.js$"
    ]
  }

For setup of Enzyme => setup.js

import { configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
configure({ adapter: new Adapter() })

For setupTestFrameworkScriptFile : setupTests.js global.fetch = require('jest-fetch-mock')

const { JSDOM } = require('jsdom')
const jsdom = new JSDOM('<!doctype html><html><body></body></html>')
const { window } = jsdom

const exposedProperties = ['window', 'navigator', 'document']
const { document } = new JSDOM('').window
global.document = document
global.window = document.defaultView
global.HTMLElement = window.HTMLElement
global.HTMLAnchorElement = window.HTMLAnchorElement

Object.keys(document.defaultView).forEach(property => {
  if (typeof global[property] === 'undefined') {
    exposedProperties.push(property)
    global[property] = document.defaultView[property]
  }
})

global.navigator = {
  userAgent: 'node.js',
}

@qyhongfan
Copy link

just .tsx files face same problem?

@joselcc
Copy link

joselcc commented Jan 29, 2019

just spreading the news, Jest v24 was updated to use Babel 7 internally, using babel bridge or babel7-jest shouldn't be needed anymore
https://twitter.com/i/web/status/1088904207653105664

@jmayergit
Copy link

jmayergit commented Feb 12, 2019

I renamed .babelrc to babel.config.js and also upgraded to Babel7 and still have the same error as before. My babel.config.js file:

module.exports = function (api) {
  api.cache(true);

  const presets = ["@babel/preset-env"];

  return {
    presets
  };
}

I installed@babel/preset-react and added it to my babel.config.js file. Fixed the error.

@rajat1saxena
Copy link

My babel.config.js file was not getting detected by babel-jest, because I put it inside __test__ directory. I moved it to the top directory where package.json was located and everything worked.

@moahammadalt
Copy link

I solved a similar problem by doing the following:

1- add enzyme setup file and write the following:

import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

Enzyme.configure({ adapter: new Adapter() });

2- add jest configuration to your package.json like that:

"jest": {
 "setupFilesAfterEnv": [
  "./path to your setup file/setupEnzyme.js"
 ]
}

3- add .babelrc file to your root path and write the following in it:

{
    "env": {
        "test": {
            "presets": [
                "@babel/preset-env",
                "@babel/preset-react"
            ]
        }
    }
}

4- if you got an error on "expect" keyword in your test just run npm install -D chai and import the expect function in your test code like that import { expect } from 'chai';

if you still get an error try to install babel dependencies like that npm install -D @babel/core @babel/preset-env @babel/preset-react

hope this helps.

@alishaevn
Copy link

alishaevn commented Feb 26, 2019

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.

My solution:

I didn't have a .babelrc file so I figured doing the reverse should work too and created a .babelrc file using the preset info from babel.config.js instead. (I created an additional file, I didn't rename the original)
Upon running the test again I received a new error: Requires Babel "^7.0.0-0", but was loaded with "6.26.3".
I googled that error and it led me here. I followed the instructions (npm install babel-core@7.0.0-bridge.0) and the test is now running and passing.

@gi-alec
Copy link

gi-alec commented Mar 1, 2019

just spreading the news, Jest v24 was updated to use Babel 7 internally, using babel bridge or babel7-jest shouldn't be needed anymore
https://twitter.com/i/web/status/1088904207653105664

Upgrading to Jest v24 fixed this issue for me :)

@rostgoat
Copy link

getting unexpected token error for

> 10 | const browser; (the semicolon at the end)

my package.json

 "dependencies": {
    "@babel/cli": "^7.2.3",
    "@babel/core": "^7.3.4",
    "@babel/register": "^7.0.0",
    "assert": "^1.4.1",
    "chai": "^4.2.0",
    "jest-puppeteer": "^4.0.0",
    "screen-info": "^1.0.1",
    "screenres": "^2.0.1"
  },
  "devDependencies": {
    "@babel/plugin-transform-modules-commonjs": "^7.2.0",
    "@babel/preset-env": "^7.3.4",
    "babel-jest": "^24.5.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-jest": "^24.3.0",
    "jest": "^24.5.0",
    "jest-cli": "^24.5.0",
    "puppeteer": "^1.13.0"
  },
  "jest": {
    "transformIgnorePatterns": [
      "/node_modules/(?!@babel).+\\.js$"
    ],
    "transform": {
      "^.+\\.js?$": "babel-jest"
    }
  },

babel.config.js

module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 'current'
        },
      },
      'jest'
    ]
  ],
  env: {
    test: {
      plugins: ['@babel/plugin-transform-modules-commonjs']
    }
  }
}

@sunmaximus
Copy link

Tested hoaiduyit solution. It work. I just need to add babel.config.js, install babel-jest transform/transpile jest in jest.config.js

@paul-3
Copy link

paul-3 commented Apr 29, 2019

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.

tks for your method~this method can fix my problem correctly!

@bjm88
Copy link

bjm88 commented Jun 12, 2019

Hi - I have tried several things in this thread, but nothing seems to be working. The main error is weird b/c it seems to point at line numbers that do not make sense, almost like the source code and actual code trying to be run do not align..

This error, Jest encountered an unexpected token, remains. I am on Jest > 24, no type script, its an ejected react-create-app pretty recently (6 months ago~). Clearing cache and removing node_modules didn't help. Perhaps someone could explain exactly what config needs to be in place for jest to properly transform and run and what hints my exact error gives...

FAIL  __e2e__/chat/sms.spec.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:

    /Users/ben/dev/app/webui/node_modules/babel-preset-react-app/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:17
    export default function _asyncToGenerator(fn) {
    ^^^^^^

    SyntaxError: Unexpected token export

       5 |   afterEach(async () => {
       6 |     await logout();
    >  7 | 
         | ^
       8 |     await page.evaluate(() => {
       9 |       localStorage.clear();
      10 |     });

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:471:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25)
      at Object.<anonymous> (__e2e__/chat/sms.spec.js:7:49)

@XinLiu1223
Copy link

Thank you all,

Jenkins fails due to this issue, is there some working solutions ?

@paulosullivan22
Copy link

For anyone using Create-React-App, adding transformignorepatterns to your package.json will not solve the issue as only certain jest configurations can be changed in package.json when using CRA.

I had issues with Jest picking up an internal library, Jest would display 'unexpected token' errors wherever I had my imports from this library.

To solve this, you can change your test script to the below:
"test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(<your-package-goes-here>)/)'",

@XW-Yanis
Copy link

XW-Yanis commented Sep 29, 2019

Hi all, I was struggling to do unit testing with my small project which is called JetSet and wrote in React Native. I searched for 2 days to solve this issue, and I had tried to edit things like babel.config.js, delete that file and then create .babel file (and add some shits).


Bug report:
D:\jetset\JetSetApp>jest SaveData.test.js
FAIL test/SaveData.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:

D:\jetset\JetSetApp\node_modules\expo-file-system\build\index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import * as FileSystem from './FileSystem';
                                                                                                ^

SyntaxError: Unexpected token *

  1 | import React, { Component } from 'react'
  2 | import { View, Text, TouchableOpacity, TextInput, StyleSheet } from 'react-native'
> 3 | import { documentDirectory, getInfoAsync, readDirectoryAsync, readAsStringAsync, writeAsStringAsync, deleteAsync } from 'expo-file-system';
    | ^
  4 |
  5 | /**
  6 |  * This class primarily serves to handle files within the phone system so that results can be stored

  at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
  at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
  at Object.<anonymous> (app/resources/SaveData/SaveData.js:3:1)

Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 3.509s
Ran all test suites matching /SaveData.test.js/i.


babel.config.js
module.exports = function(api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
};
};


package.json
{
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"eject": "expo eject",
"test": "jest"
},
"jest": {
"preset": "react-native"
},
"dependencies": {
"expo": "^34.0.1",
"expo-file-system": "^6.0.2",
"expo-mail-composer": "^6.0.0",
"moment": "^2.24.0",
"react": "16.8.3",
"react-dom": "^16.8.6",
"react-native": "https://github.com/expo/react-native/archive/sdk-34.0.0.tar.gz",
"react-native-gesture-handler": "^1.3.0",
"react-native-selection-group": "^1.1.2",
"react-native-web": "^0.11.4"
},
"devDependencies": {
"@babel/core": "^7.6.2",
"@babel/preset-env": "^7.6.2",
"babel-jest": "^24.9.0",
"babel-preset-expo": "^6.0.0",
"jest": "^24.9.0",
"prop-types": "^15.7.2",
"react-native-dismiss-keyboard": "^1.0.0",
"react-native-modal-datetime-picker": "^7.5.0",
"react-navigation": "^3.12.1"
},
"private": true
}

@bjm88
Copy link

bjm88 commented Sep 29, 2019

FYI I think we ended up finding a really silly solution to this, like the entire build system wasn't behaving well if NODE_ENV="test" wasm't set.

@sbland
Copy link

sbland commented Oct 4, 2019

In the newer versions of React Jest is built in therefore in package.json the test script should be
"test": "react-scripts test"
instead of
"test": "jest"

@tsarg88
Copy link

tsarg88 commented Oct 13, 2019

In the newer versions of React Jest is built in therefore in package.json the test script should be
"test": "react-scripts test"
instead of
"test": "jest"

Thanks a lot, that solved the issue for me!

@artdias90
Copy link

artdias90 commented Nov 19, 2019

After trying a LOT, the problem for me:
missing "transform-es2015-modules-commonjs", on .babelrc file

{
  "presets": ["next/babel"],
  "plugins": [
    ["styled-components", { "ssr": true, "displayName": true, "preprocess": false } ],
    "transform-flow-strip-types",
    "jsx-control-statements",
    "import-glob",
    "transform-es2015-modules-commonjs",
    [
      "import",
      {
        "libraryName": "antd",
        "style": "css"
      }
    ]
  ]
}

"jest": "^24.9.0",
"babel-jest": "23.6.0",

@97thjingba
Copy link

try to update your jest and babel-jest

@amirsaeed671
Copy link

I renamed .babelrc to babel.config.js and also upgraded to Babel7 and still have the same error as before. My babel.config.js file:

module.exports = function (api) {
  api.cache(true);

  const presets = ["@babel/preset-env"];

  return {
    presets
  };
}

I installed@babel/preset-react and added it to my babel.config.js file. Fixed the error.

this fixed my problem, I installed @babel/preset-env and added to babel.config.js and it fixed

thanks @jmayergit

@smiti-maheshwari
Copy link

I had changed the babel.rc file to babel.config.js file but it wasn't working for me. Then I saw this answer: https://stackoverflow.com/questions/58470062/test-jest-with-babel-plugin-import
If one has import plugins, separate out the plugins for test, dev and production environments.

My babel.config.js file now looks like this which works:

module.exports = {
  presets: [
    [
      'next/babel',
    ],
  ],
  env: {
    test: {

    },
    dev: {
      plugins: [
        ['import', { libraryName: 'antd', style: 'css' }],
      ],
    },
    production: {
      plugins: [
        ['import', { libraryName: 'antd', style: 'css' }],
      ],
    },
  },
};

@fullstacksk
Copy link

I am also struggling with this error from 5 days

    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:\Users\SK-PC\Desktop\React-Course\expansify\src\test\components\MyNavbar.test.js: Unexpected token (5:28)

      3 | import { MyNavbar } from '../../components/MyNavbar'
      4 | test("Should return MyNavbar component", () => {
    > 5 |     const wrapper = shallow(<MyNavbar />)
        |                             ^
      6 |     expect(wrapper.find('.navbar-brand').find('kbd').text()).toBe("Expensify")
      7 |     // const renderer = new ReactShallowRenderer()
      8 |     // renderer.render(<MyNavbar />)

      at Parser._raise (node_modules/@babel/parser/src/parser/location.js:241:45)
      at Parser.raiseWithData (node_modules/@babel/parser/src/parser/location.js:236:17)
      at Parser.raise (node_modules/@babel/parser/src/parser/location.js:220:17)
      at Parser.unexpected (node_modules/@babel/parser/src/parser/util.js:149:16)
      at Parser.parseExprAtom (node_modules/@babel/parser/src/parser/expression.js:1144:20)
      at Parser.parseExprSubscripts (node_modules/@babel/parser/src/parser/expression.js:539:23)
      at Parser.parseMaybeUnary (node_modules/@babel/parser/src/parser/expression.js:519:21)
      at Parser.parseExprOps (node_modules/@babel/parser/src/parser/expression.js:311:23)
      at Parser.parseMaybeConditional (node_modules/@babel/parser/src/parser/expression.js:263:23)
      at Parser.parseMaybeAssign (node_modules/@babel/parser/src/parser/expression.js:211:21)

 PASS  src/test/reducers/filters.test.js

Test Suites: 1 failed, 5 passed, 6 total
Tests:       29 passed, 29 total
Snapshots:   0 total
Time:        12.144s
Ran all test suites.

@catmans1
Copy link

catmans1 commented Apr 21, 2020

@fullstacksk

In the newer versions of React Jest is built in therefore in package.json the test script should be
"test": "react-scripts test"
instead of
"test": "jest"

You could read document at:
https://jestjs.io/docs/en/tutorial-react
https://create-react-app.dev/docs/running-tests/#docsNav

@fullstacksk
Copy link

@catmans1
I have not installed dependencies like create-react-app or react-scripts.
Will it work?
"test": "react-scripts test"
instead of
"test": "jest"

@fullstacksk
Copy link

Now it is working, when I used babel-preset-jest for testing option with env and react. I have removed babel-jeast.

@vanessamcf
Copy link

Worked for me: include β€œ@babel/preset-react” at babel.config.js

https://medium.com/@audreyhal/how-to-solve-jest-error-with-create-react-app-part-1-80f33aa1661a

@gpawlik
Copy link

gpawlik commented Sep 10, 2020

I saw this error after making a stupid mistake and writing my first test file with .ts instead of .tsx extension. Far from the original issue but i though it might be helpful for someone πŸ˜„

@ufukomer
Copy link

ufukomer commented Jan 7, 2021

For anyone using Create-React-App, adding transformignorepatterns to your package.json will not solve the issue as only certain jest configurations can be changed in package.json when using CRA.

I had issues with Jest picking up an internal library, Jest would display 'unexpected token' errors wherever I had my imports from this library.

To solve this, you can change your test script to the below:
"test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(<your-package-goes-here>)/)'",

Worked for me:

craco test --transformIgnorePatterns \"node_modules/(?!@qbloomy)/\""

@theankurkedia
Copy link

In case anyone is facing this with React-Native, you can check out babel's transformIgnorePatterns. It says that since some modules are untranspiled, you will need to add them here.

@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators May 11, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests