jest: Unexpected token export

I use react-icons in my component and when I try to render it with react-test-render I get this:

`“C:\Program Files\JetBrains\WebStorm 2016.2.2\bin\runnerw.exe” “C:\Program Files\nodejs\node.exe” “C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js” test

another-todo@0.1.0 test C:\study\reactodo node scripts/test.js --env=jsdom

FAIL src\components\category-tree\category-tree.component.test.js ● Test suite failed to run

C:\study\reactodo\node_modules\react-icons\fa\angle-down.js:5
export default class FaAngleDown extends React.Component {
^^^^^^
SyntaxError: Unexpected token export
  
  at transformAndBuildScript (node_modules\jest-runtime\build\transform.js:284:10)
  at Object.<anonymous> (src\components\category\category.component.js:2:44)
  at Object.<anonymous> (src\components\category-tree\category-tree.component.js:4:184)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        6.59s
Ran all test suites related to changed files.

Watch Usage
 › Press a to run all tests.
 › Press o to only run tests related to changed files.
 › Press p to filter by a filename regex pattern.
 › Press q to quit watch mode.
 › Press Enter to trigger a test run.`

This is how C:\study\reactodo\node_modules\react-icons\fa\angle-down.js looks like:

let React = require('react');
let IconBase = require('react-icon-base');

export default class FaAngleDown extends React.Component {
    render() {
    return (
        <IconBase viewBox="0 0 40 40" {...this.props}>
            <g><path d="m31 16.4q0 0.3-0.2 0.5l-10.4 10.4q-0.3 0.3-0.5 0.3t-0.6-0.3l-10.4-10.4q-0.2-0.2-0.2-0.5t0.2-0.5l1.2-1.1q0.2-0.2 0.5-0.2t0.5 0.2l8.8 8.8 8.7-8.8q0.3-0.2 0.5-0.2t0.6 0.2l1.1 1.1q0.2 0.2 0.2 0.5z"/></g>
        </IconBase>
    );
    }
}

Why is export unexpected here?

This is what my test looks like:

import renderer from 'react-test-render';
import CategoryTree from './category-tree.component';
import {categories} from '../../../testing-utils/deep-nested-category-tree';
import {LIST_MODE, DETAIL_MODE} from '../category/category.component'

test('CategogryTree renders correctly', () => {
const tree = renderer.create(
	<CategoryTree categories={categories} categoriesMode={LIST_MODE} selectedCategory={'1'} todo={{}} />
).toJSON();
expect(tree).toMatchSnapshot();
});

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 43
  • Comments: 47 (4 by maintainers)

Most upvoted comments

For now try setting this:

"transformIgnorePatterns": [
  "node_modules/?!(react-icons)"
]

You can also check this thread on customising .babelrc: https://github.com/facebook/jest/issues/2442#issuecomment-269654883

transformIgnorePatterns

This response is to help people further understand this issue

If you check the Jest docs here you will get an explanation as to why this is happening. You should read it.

Redefining the issue

By default Jest will ignore transpiling everything in the node_modules directory when it runs your tests. All of your installed dependencies may not provide their code in the transpiled format. There is nothing you can do really do to fix this, unless you want to make a contribution to their project and change their build. When Jest encounters this JavaScript in your tests (like in an export) it does not know what to do with it and throws a syntax error like the one above.

Solution

If you are having this issue, you will need to tell Jest what things you want to be transpiled with something like babel-jest. You do this by overriding the default value for transformIgnorePatterns. There a couple different places to define this configuration. I did mine in a jest.config.js file at the root of my project. You can also do it in your package.json. Check this link.

The below file was mainly created by create-react-app but was updated to allow transpiling on 2 project dependencies. Look at the regular expression in transformIgnorePatterns array. It tells Jest not to transpile the node_modules but to transpile the two named dependencies: transpile-me and transpile-me-too.

module.exports = {
  collectCoverageFrom: [
    'src/**/*.{js,jsx}'
  ],
  setupFiles: [
    '<rootDir>/config/polyfills.js'
  ],
  testMatch: [
    '<rootDir>/src/**/__tests__/**/*.js?(x)',
    '<rootDir>/src/**/?(*.)(spec|test).js?(x)'
  ],
  testEnvironment: 'node',
  testURL: 'http://localhost',
  transform: {
    '^.+\\.(js|jsx)$': '<rootDir>/node_modules/babel-jest',
    '^.+\\.css$': '<rootDir>/config/jest/cssTransform.js',
    '^(?!.*\\.(js|jsx|css|json)$)': '<rootDir>/config/jest/fileTransform.js'
  },
  transformIgnorePatterns: [
    '/node_modules/(?!transpile-me|transpile-me-too).+(js|jsx)$'
  ],
  moduleFileExtensions: [
    'web.js',
    'js',
    'json',
    'web.jsx',
    'jsx',
    'node'
  ],
  modulePaths: [
    'src'
  ]
}

You can | as many additional dependencies as you need. I would suggest only adding dependencies that you get errors from. No need to try to be proactive here.

Hope this helps!

I’m currently seeing similar issue. Here is my package.json file:

{ “name”: “publish-apps”, “version”: “1.0.0”, “private”: true, “engines”: { “node”: “=8.11.4”, “npm”: “=6.4.1” }, “dependencies”: { “@microsoft/sp-core-library”: “1.7.0”, “@microsoft/sp-lodash-subset”: “1.7.0”, “@microsoft/sp-office-ui-fabric-core”: “1.7.0”, “@microsoft/sp-webpart-base”: “1.7.0”, “@types/adal”: “1.0.27”, “@types/angular”: “1.6.32”, “@types/es6-collections”: “0.5.31”, “@types/es6-promise”: “0.0.33”, “@types/jest”: “20.0.8”, “@types/nock”: “8.2.1”, “@types/prop-types”: “15.5.2”, “@types/react”: “16.4.2”, “@types/react-addons-shallow-compare”: “0.14.17”, “@types/react-addons-test-utils”: “0.14.15”, “@types/react-addons-update”: “0.14.14”, “@types/react-dom”: “16.0.5”, “@types/react-redux”: “5.0.9”, “@types/redux-logger”: “3.0.4”, “@types/request”: “2.0.3”, “@types/webpack-env”: “1.13.1”, “@uifabric/styling”: “0.24.2”, “@uifabric/utilities”: “4.16.0”, “adal-angular”: “1.0.12”, “applicationinsights-js”: “1.0.13”, “identity-obj-proxy”: “3.0.0”, “immutable”: “3.8.1”, “jest”: “20.0.4”, “moment”: “2.22.2”, “office-ui-fabric-react”: “6.1.0”, “phantomjs-prebuilt”: “2.1.16”, “react”: “16.3.2”, “react-appinsights”: “1.0.2”, “react-dom”: “16.3.2”, “react-redux”: “5.0.4”, “redux”: “3.7.2”, “ts-lint”: “4.5.1”, “tslint”: “5.11.0”, “tslint-react”: “3.2.0”, “typescript”: “3.1.6” }, “devDependencies”: { “@microsoft/sp-build-web”: “1.7.0”, “@microsoft/sp-module-interfaces”: “1.7.0”, “@microsoft/sp-tslint-rules”: “1.7.0”, “@microsoft/sp-webpart-workbench”: “1.7.0”, “@types/chai”: “3.4.34”, “@types/enzyme”: “3.1.11”, “@types/enzyme-adapter-react-16”: “1.0.3”, “@types/jest”: “23.1.1”, “@types/mocha”: “2.2.38”, “@types/validator”: “9.4.2”, “ajv”: “5.2.2”, “enzyme”: “3.3.0”, “enzyme-adapter-react-16”: “1.7.0”, “gulp”: “3.9.1”, “gulp-spsync-creds”: “2.3.7”, “jest”: “23.1.0”, “jest-cli”: “20.0.4”, “jest-junit”: “5.1.0”, “nock”: “9.0.14”, “node-sppkg-deploy”: “1.1.2”, “raf”: “3.4.0”, “react-test-renderer”: “16.3.2”, “redux-devtools”: “3.4.0”, “redux-logger”: “3.0.6”, “redux-mock-store”: “1.2.3”, “redux-thunk”: “2.2.0”, “sinon”: “6.3.5”, “ts-jest”: “22.4.6”, “tslint-microsoft-contrib”: “5.0.0”, “tslint-react”: “3.6.0” }, “jest”: { “moduleFileExtensions”: [ “ts”, “tsx”, “js”, “jsx”, “json” ], “transform”: { “\.(ts|tsx)$”: “<rootDir>/node_modules/ts-jest/preprocessor.js” }, “testRegex”: “.\.test\.(ts|tsx)$", “testPathIgnorePatterns”: [ "src/././././interfaces/.”, “src/././././reducers/." ], “collectCoverage”: true, “setupFiles”: [ “raf/polyfill” ], “coverageReporters”: [ “json”, “lcov”, “text”, “cobertura” ], “coverageDirectory”: “<rootDir>/jest”, “moduleNameMapper”: { “\.(css|less|scss|sass)$”: “identity-obj-proxy” }, “reporters”: [ “default”, “jest-junit” ], “coverageThreshold”: { “global”: { “branches”: 51, “functions”: 53, “lines”: 66, “statements”: 60 } }, “collectCoverageFrom”: [ "**/.{ts,tsx}”, “!/*.d.{ts,tsx}", "!/.scss.ts", “!/models/”, “!/node_modules/”, “!/src/index.ts", "!/src/webparts/publishApps/RootReducer.ts”, "!**/src/webparts/publishApps/interfaces/.ts”, “!/src/webparts/publishApps/Components//interfaces/.ts", "!/src/webparts/publishApps/Components//reducers/”, “!/src/webparts/I*.ts", "!/src/webparts/publishApps/I*.ts”, “!/src/webparts/publishApps/*.ts", "!/src/webparts/publishApps/store/", "!**/src/webparts/publishApps/reducers/” ] }, “scripts”: { “preinstall”: “(npm cache clean --force) && (npm list npm@6.4.1 -g || npm install npm@6.4.1 -g) && (npm list gulp@3.9.1 -g || npm install gulp@3.9.1 -g)”, “build”: “gulp bundle”, “clean”: “gulp clean”, “test”: “jest” }, “jest-junit”: { “output”: “./jest/summary-jest-junit.xml” } }

@meetbabu if you want to whitelist @swish so it gets transformed, use:

"transformIgnorePatterns": [ "<roodDir>/node_modules/(?!@swish)" ]

(?!) is a regex negative lookahead, you can go to http://regexr.com/ and tweak your regex as you like 😃

I’ve tried all the solutions mentioned in this thread, and it was working until we introduced babel-plugin-transform-imports. It converts imports like

import { Foo, Bar } from '@material-ui/icons';

into

import Foo from '@material-ui/icons/esm/Foo';
import Bar from '@material-ui/icons/esm/Bar';

thus avoiding pulling in all the icons when we only use one or two.

I added:

  transformIgnorePatterns: [
    "node_modules/(?!@material-ui)",
  ],

to inform Jest these still need transforming.

This results in errors like:

    .../node_modules/@material-ui/core/esm/Table/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){export { default } from './Table';
                                                                                             ^^^^^^

    SyntaxError: Unexpected token export

[I tried asking in discord, but had 0 response after a week, so am piling on here.]

The only way I’ve been able to resolve it is via --no-cache with every run. 🤷‍♂️

Thank you @thymikee My solucition with react-router-native

...
"transformIgnorePatterns": [ 
  "node_modules/?!(react-router-native)" 
]
...

Include JS files in your transform:

"transform": {
  "^.+\\.(js|jsx|ts|tsx)$": "<rootDir>/jest/jestpreprocessor.js"
},

No, please read the Babel docs.

@rahamin1 easiest you can do is:

  1. Install latest Jest 24 (with better Babel 7 support)
yarn add --dev jest babel-jest @babel/core 
  1. Make sure you use babel.config.js for Babel config
  2. Remove "transform" from Jest config because it’s covered by "react-native" preset
    ],
-    "transform": {
-      "^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js",
-      "^.+\\.jsx?$": "babel-jest"
-    },
    "transformIgnorePatterns": [

This error shouldn’t have happend. Try to type it instead of copying, maybe you’ve copied some whitespace. In the meantime file an issue in react-icons about missing "main" field. They’re building the files on prepublish but don’t link to it, so node doesn’t know where to look for compiled output.

The solution was to specify all the modules of the package that caused the problem (victory-native|victory-core|victory-shared-events|victory-area etc. instead of victory-*)

Hi! @dKab I had the same problem and I solved it by import from react-icons/lib instead of from react-icons This approach is explained in the readme from the project here: https://github.com/gorangajic/react-icons#usage

I hope this is of some use for you!

I had the same issue, as I’m trying to use ./src/node_modules for internal libs.

Fix:

// .jestrc
 "transformIgnorePatterns": [
    "<rootDir>/(node_modules)/"
  ]

The default regex should have <rootDir> in it:

https://github.com/facebook/jest/blob/e6495647112781b98ff194fe34952a8139f045df/packages/jest-validate/src/__tests__/fixtures/jestConfig.js#L16