54

Not sure why it's complaining on this line:

const wrapper = shallow(<BitcoinWidget {...props} />);

/Users/leongaban/projects/match/bitcoin/src/components/bitcoinWidget.test.js: Unexpected token (17:26)

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:
  15 |
  16 | describe('when rendering', () => {
 >17 |   const wrapper = shallow(<BitcoinWidget {...props} />);
  18 |                           ^
  19 |   it('should render a component matching the snapshot', () => {
  20 |     const tree = toJson(wrapper);

Entire test:

import React from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';

// Local components
import BitcoinWidget from './bitcoinWidget';

const props = {
  logo: 'foobar',
  coin: {
    price: 0
  },
  refresh: jest.fn()
}

describe('when rendering', () => {
  const wrapper = shallow(<BitcoinWidget {...props} />);

  it('should render a component matching the snapshot', () => {
    const tree = toJson(wrapper);
    expect(tree).toMatchSnapshot();
    expect(wrapper).toHaveLength(1);
  });
});

The component

import React from 'react';

const BitcoinWidget = ({ logo, coin : { price }, refresh }) => {
  return (
    <div className="bitcoin-wrapper shadow">
      <header>
        <img src={logo} alt="Bitcoin Logo"/>
      </header>
      <div className="price">
        Coinbase
        ${price}
      </div>
      <button className="btn striped-shadow white" onClick={refresh}>
        <span>Refresh</span>
      </button>
    </div>
  );
}

export default BitcoinWidget;

And my package.json

{
  "name": "bitcoin",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "axios": "^0.18.0",
    "react": "^16.4.2",
    "react-dom": "^16.4.2",
    "react-redux": "^5.0.7",
    "react-scripts": "1.1.5",
    "redux": "^4.0.0",
    "redux-thunk": "^2.3.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "eject": "react-scripts eject",
    "test": "yarn run test-jest:update --verbose --maxWorkers=2",
    "test-jest:update": "jest src --updateSnapshot",
    "test-jest": "jest src"
  },
  "now": {
    "name": "bitcoin",
    "engines": {
      "node": "8.11.3"
    },
    "alias": "leongaban.com"
  },
  "jest": {
    "verbose": true,
    "moduleNameMapper": {
      "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/client/assetsTransformer.js"
    },
    "moduleFileExtensions": [
      "js",
      "jsx"
    ],
    "moduleDirectories": [
      "node_modules"
    ]
  },
  "devDependencies": {
    "enzyme": "^3.4.4",
    "enzyme-to-json": "^3.3.4",
    "jest": "^23.5.0"
  }
}
0

10 Answers 10

15

Add this in your package.json jest config.

"transform": {
      "\\.js$": "<rootDir>/node_modules/babel-jest"
    },

Let me know if the issue still persists.

2
  • 2
    I was also missing babel-plugin-transform-es2015-destructuring babel-plugin-transform-object-rest-spread enzyme-adapter-react-15 eslint-config-airbnb
    – Leon Gaban
    Aug 23, 2018 at 21:50
  • This would be a better answer, if it explained WHY this is the fix. That way, other people can judge if the same or similar fix will work for them.
    – Stewart
    Nov 27 at 10:11
11

For anyone using create-react-app, only certain jest configurations can be changed in package.json when using create-react-app.

I have 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>)/)'",

3
  • This worked for me, in a similar case of using external lib.
    – jckmlczk
    Apr 6, 2022 at 11:59
  • 3
    I have a CRA TS app and was getting import error for axios while testing. I updated the test script to react-scripts test --transformIgnorePatterns \"node_modules/(?!axios)/\" --env=jsdom and it worked. Thanks! Oct 12, 2022 at 4:42
  • 1
    As noted by @sohammondal you should use double quotes instead of single quotes.
    – humleflue
    Nov 18, 2022 at 17:47
10

For anyone who struggled with this issue and none of the above answers worked for them.

After a long time of searching, I reached for this solution:

edit your jest.config.js to add transformIgnorePatterns

//jest.config.js

module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'jsdom',
    testMatch: ["**/__tests__/**/*.ts?(x)", "**/?(*.)+(test).ts?(x)"],
    transform: {
        "^.+\\.(js|ts)$": "ts-jest",
    },
    transformIgnorePatterns: [
        "/node_modules/(?![@autofiy/autofiyable|@autofiy/property]).+\\.js$",
        "/node_modules/(?![@autofiy/autofiyable|@autofiy/property]).+\\.ts$",
        "/node_modules/(?![@autofiy/autofiyable|@autofiy/property]).+\\.tsx$",
    ],
}

put the packages that you want to ignore inside [] and separate them by |

in my case [@autofiy/autofiyable|@autofiy/property]

2
  • honestly, I don't know that is the reason that led to this issue
    – Ali Faris
    Jan 16, 2021 at 16:09
  • And this is what was suggested by Jest in the first line of the error message (see the original question)
    – Dmitriy
    Jun 20, 2022 at 3:46
5

I added the jest update to my package.json

"jest": {
  "transformIgnorePatterns": [
    "node_modules/(?!(<package-name>|<second-package-name>)/)"
  ]
},

Feel free to remove the |<second-package-name> if not required.

You can also do it as part of your script as mentioned @paulosullivan22

"test": "react-scripts test --transformIgnorePatterns 'node_modules/(?!(<package-name>)/)'"

0
4

I also encountered the same error while setting up Jest in my React app created using Webpack. I had to add @babel/preset-env and it was fixed. I have also written a blog article about the same.

npm i -D @babel/preset-env

And then add this in "presets" in .babelrc file. E.g.

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

https://medium.com/@shubhgupta147/how-i-solved-issues-while-setting-up-jest-and-enzyme-in-a-react-app-created-using-webpack-7e321647f080?sk=f3af93732228d60ccb24b47ef48d7062

2

I updated some dependencies (react, jest and others), and I also got the error:

Jest encountered an unexpected token - SyntaxError: Cannot use import statement outside a module

I had dev dependencies with needed to be transpiled.

What I did first was start all over:

$ jest --init

A jest.config.js is now generated (before I just had Jest configuration in my package.json).

In the error message under details you can see the reporting module, for me it looked like this:

Details: /<project_root>/node_modules/axios/index.js:1

Adding the following transform ignore in jest.config.js solved my problem:

transformIgnorePatterns: [
    "node_modules/(?!axios.*)"
],

The axios module was now nicely transpiled and gave no more problems, hope this helps!

1

In my case, the issue was that I was importing the original module in the mocked module:

import urlExist from "url-exist";

async function stubbedUrlExist(): Promise<boolean> {
  // do something
}

export default stubbedUrlExist;

The solution was to not import url-exist in the url-exist mock. This might have lead to a circular import. Jest was perhaps catching this error in a generic try<>catch block dealing with the loading of modules.

1

Below works for me. Create babel.config.js file.

module.exports = {
  presets: [
    [ '@babel/preset-env', { targets: { esmodules: true } } ],
    [ '@babel/preset-react', { runtime: 'automatic' } ],
  ],
};
0

Below works for me

module.exports = {
  presets: [
    ["@babel/preset-env", { targets: { node: "current" } }],
    "@babel/preset-typescript", "@babel/react"
  ]
};
0

could not get it working with transforms, I ended up mocking the dependency:

Create a file: <path>/react-markdown.js

import React from 'react';

function ReactMarkdown({ children }){
  return <>{children}</>;
}

export default ReactMarkdown;

On jest.config.js file add:

module.exports = {
  moduleNameMapper: {
    'react-markdown': '<path>/mocks/react-markdown.js',
  },
};

credits to juanmartinez on https://github.com/remarkjs/react-markdown/issues/635

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.