Skip to content Skip to sidebar Skip to footer

Testing React Components: Jest Encountered An Unexpected Token

I am trying to test with Jest, but got an error: Jest encountered an unexpected token This usually means that you are trying to import a file which Jest cannot parse, e.g. i

Solution 1:

Here it is the same problem: Jest Error Unexpected token on react component

You need to add a .babelrc file with:

{"presets":["env","react"]}

Solution 2:

I solved a similar problem by doing the following:

1- add enzyme setup file and write the following:

importEnzymefrom'enzyme';
importAdapterfrom'enzyme-adapter-react-16';

Enzyme.configure({ adapter: newAdapter() });

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.

Post a Comment for "Testing React Components: Jest Encountered An Unexpected Token"