Leon Gaban
Leon Gaban

Reputation: 39018

Jest encountered an unexpected token

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"
  }
}

Upvotes: 64

Views: 136451

Answers (10)

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

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

Upvotes: 1

Ali Faris
Ali Faris

Reputation: 18592

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]

Upvotes: 15

FrankyHollywood
FrankyHollywood

Reputation: 1773

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!

Upvotes: 3

FrankyHollywood
FrankyHollywood

Reputation: 1773

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

Upvotes: 0

Dude Named Ben
Dude Named Ben

Reputation: 1

Below works for me

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

Upvotes: 0

Roger Perez
Roger Perez

Reputation: 3139

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

Upvotes: 7

Paul Razvan Berg
Paul Razvan Berg

Reputation: 21400

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.

Upvotes: 1

Shubham Gupta
Shubham Gupta

Reputation: 53

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

Upvotes: 5

paulosullivan22
paulosullivan22

Reputation: 330

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

Upvotes: 15

Sakhi Mansoor
Sakhi Mansoor

Reputation: 8102

Add this in your package.json jest config.

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

Let me know if the issue still persists.

Upvotes: 17

Related Questions