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

Unexpected token export #2550

Closed
dKab opened this issue Jan 10, 2017 · 47 comments
Closed

Unexpected token export #2550

dKab opened this issue Jan 10, 2017 · 47 comments

Comments

@dKab
Copy link

dKab commented Jan 10, 2017

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

[email protected] 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();
});
@thymikee
Copy link
Collaborator

Checkout this thread: #2488

@dKab
Copy link
Author

dKab commented Jan 10, 2017

@thymikee Are you sure it is the same as #2488 ? It seems to be react-native related issue and mine is about react.

@thymikee
Copy link
Collaborator

Not the same but it looks like the reason is the same – code from react-icons doesn't get transpiled (its package.json desn't provide a "main" field, maybe that's the case), so you have to explicitly tell jest to transpile it with babel transform

@dKab
Copy link
Author

dKab commented Jan 10, 2017

@thymikee

so you have to explicitly tell jest to transpile it with babel transform

Sorry, would you be so kind and point me in the right direction on how to do that?

@thymikee
Copy link
Collaborator

For now try setting this:

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

You can also check this thread on customising .babelrc: #2442 (comment)

@dKab
Copy link
Author

dKab commented Jan 10, 2017

I use create-react-app and it seems it stores config for jest in package.json (at least I have a propery jest there):

"jest": {
    "moduleFileExtensions": [
      "jsx",
      "js",
      "json"
    ],
    "moduleNameMapper": {
      "^.+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/config/jest/FileStub.js",
      "^.+\\.css$": "<rootDir>/config/jest/CSSStub.js"
    },
    "setupFiles": [
      "<rootDir>/config/polyfills.js"
    ],
    "testPathIgnorePatterns": [
      "<rootDir>/(build|docs|node_modules)/"
    ],
    "testEnvironment": "node"
  },

But when I try to add


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

it says

Error: Unknown config option "transformIgnorePatterns" with value "node_modules/?!(react-icons)". This is either a typing error or a user mistake and fixing it will remove this message.

@thymikee
Copy link
Collaborator

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.

@dKab
Copy link
Author

dKab commented Jan 10, 2017

@thymikee

This error shouldn't have happend. Try to type it instead of copying, maybe you've copied some whitespace.

strange but the same happens when I try to add transform option.

@thymikee
Copy link
Collaborator

Are you trying this under jest key? Maybe it's a bug in CRA then

@dKab
Copy link
Author

dKab commented Jan 10, 2017

Are you trying this under jest key?

yes 😢

@ericclemmons
Copy link
Contributor

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

@meetbabu
Copy link

@dKab is it working for you? I have the same problem and the suggested fix is not working, tried both
"transformIgnorePatterns": [ "node_modules/?!(@swish)" ]
and
"transformIgnorePatterns": [ "<rootDir>/(node_modules)/" ]
@swish is my internal library. still getting the same error

@thymikee
Copy link
Collaborator

@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 :)

@meetbabu
Copy link

thanks @thymikee, even with the right expression I am still getting the error, here is my jestconfig.json

{
  "verbose": true,
    "transform": {
      "^.+\\.(ts|tsx)$": "<rootDir>/jest/jestpreprocessor.js"
    },
    "transformIgnorePatterns": [ "<roodDir>/node_modules/(?!@swish)" ],
    "testRegex": "(/__tests__/.*|\\.?(test|spec|Test|Spec))\\.(ts|tsx|js|jsx)$",
    "moduleFileExtensions": [ "ts", "tsx", "js", "jsx" ],
    "testResultsProcessor": "<rootDir>/node_modules/ts-jest/coverageprocessor.js",
    "modulePaths":["<rootDir>/node_modules", "<rootDir>/src"],
    "moduleNameMapper": {
        "^.+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/jest/jestfilemock.js",
        "^.+\\.(css|scss)$": "<rootDir>/jest/jeststylemock.js"
    }
}

I have a simple file that uses a simple library in @swish and I am getting the below error

FAIL  src/pages/app/__tests__/SimpleHeaderTest.tsx
  ● Test suite failed to run

    /Users/Babu/Projects/swish/gitworkspace/ui/ui-app-mobile/node_modules/@swish/ui-components/di
st/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){expo
rt * from './actions';
                                                                                             ^^^^
^^
    SyntaxError: Unexpected token export

      at e (node_modules/jest-runtime/build/transform.js:320:12)
      at Object.<anonymous> (src/pages/app/SimpleHeader.tsx:14:23)
      at Object.<anonymous> (src/pages/app/__tests__/SimpleHeaderTest.tsx:8:22)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        2.058s
Ran all test suites.

any advice where to look for the fix?

@thymikee
Copy link
Collaborator

Include JS files in your transform:

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

@meetbabu
Copy link

meetbabu commented Apr 1, 2017

thank you @thymikee, it is working with these changes.

@duduindo
Copy link

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

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

@marcusjwhelan
Copy link

marcusjwhelan commented May 25, 2017

@thymikee I have tried everything under the sun looking up all issues related to this one, but can not seem to get rid of this error. I am importing a package written by myself that is TypeScript using module system 'es6' and the current package I am working on is using module system 'system'. I have switched them both around to see if that was the issue but it seems that is not the problem.

Should I open up a new issue with a more descriptive explanation of everything I have tried with linked issues?

my jest config.

{
    "rootDir": "../",
    "globals": {
        "__TS_CONFIG__": "<rootDir>/spec/tsconfig.json"
    },
    "transformIgnorePatterns": [
        "<rootDir>/node_modules/(?!binary-type-tree)"
    ],
    "transform": {
        "^.+\\.(js|ts)$": "<rootDir>/spec/preprocessor.js"
    },
    "moduleDirectories": [
        "node_modules",
        "node_modules/@types"
    ],
    "testRegex": "(/^spec/.*|\\.(test|spec))\\.(ts|js)$",
    "moduleFileExtensions": [
        "ts",
        "js"
    ]
}

the preprocessor is the recommended typescript preprocessor jest example

dependencies

"dependencies": {
    "binary-type-tree": "^1.0.5"
  },
  "devDependencies": {
    "@types/jest": "^19.2.3",
    "@types/node": "^7.0.22",
    "jest": "^20.0.3",
    "typescript": "^2.3.2"
  }

@WhynoChinese
Copy link

I had the same issue...
image

@ericclemmons
Copy link
Contributor

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

@acamposruiz
Copy link
Contributor

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!

@jordanpapaleo
Copy link

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!

@MadeleineCodes
Copy link

I had a similar issue after introducing yarn workspaces. Suddenly the tests were not working anymore.
The fix for me was to put .babelrc file in the root folder as well (some packages do not use babel and have no own .babelrc file).

@dahfool
Copy link

dahfool commented Oct 9, 2018

I am using the latest version of Create React App, after reading some of the comments above, this is my fix dahfool/pati@3edc3ee to make unit tests on Webstorm.

{
  "devDependencies": {
    "react-scripts": "2.0.4"
  },
  "dependencies": {
    "react": "^16.5.2",
    "react-dom": "^16.5.2"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

@thymikee
Copy link
Collaborator

No, please read the Babel docs.

@rahamin1
Copy link

Tried your suggestions. Doesn't work...

@SimenB
Copy link
Member

SimenB commented Jan 26, 2019

Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@rahamin1
Copy link

Tried in SO as well...

@rahamin1
Copy link

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-*)

@lipalath-ms
Copy link

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)$": "/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": "/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 [email protected] -g || npm install [email protected] -g) && (npm list [email protected] -g || npm install [email protected] -g)",
"build": "gulp bundle",
"clean": "gulp clean",
"test": "jest"
},
"jest-junit": {
"output": "./jest/summary-jest-junit.xml"
}
}

@adrian-moisa
Copy link

Several bugfixes were needed, and I managed to get the tests running:

  • Eliminates unknown "export" token: "Unexpected token export, when import not compiled libraries"
"transformIgnorePatterns": [
    "node_modules/?!(react-router)"
],
  • Removed jsdom - no longer emulating browser environment for react native. "TypeError: Cannot set property '_eventListeners' of undefined” with jest"
  • Updated: testPathIgnorePatterns to ignore all folders except "src" so we can remove roots: ["src"] which causes: "Cannot find module 'setupDevtools' from 'setup.js'"

@cleverbeagle
Copy link

Just in case someone turns on doofus mode like me: if you're not in a project with any transpiled/compiled code, you don't need this (copied my config from a project that DID use Babel to one that didn't). Double-check you actually need this. If not, remove it and any Babel-related code out of the project (e.g., any Babel deps, .babelrc, etc) and you should be good to go.

@karltaylor
Copy link

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

If someone comes across this, when I ran --no-cache it was fine, after that all other test runs ran fine.

@funkybob
Copy link

funkybob commented Nov 8, 2019

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.]

@funkybob
Copy link

Have confirmed the issue is an interaction with babel-plugin-transform-imports

@baixiaoji
Copy link

Have confirmed the issue is an interaction with babel-plugin-transform-imports

so the solution is add the babel-plugin-transform-imports or remove it

@funkybob
Copy link

The solution we've gone with is to change the transform-imports plugin to not pull in the ESM version of the code, but instead commonjs variant.

@simkessy
Copy link

simkessy commented May 4, 2020

The solution we've gone with is to change the transform-imports plugin to not pull in the ESM version of the code, but instead commonjs variant.

Can you show your settings?

@drugoi
Copy link

drugoi commented Jun 22, 2020

Hey, @funkybob, can you provide your solution, please?

I've stuck with same problem.

@funkybob
Copy link

In our babel plugins config we have:

    [
      "transform-imports",
      {
        "@material-ui/icons": {
          "transform": "@material-ui/icons/${member}",
          "preventFullImport": true
        },
        "@material-ui/core": {
          "transform": "@material-ui/core/${member}",
          "preventFullImport": true
        },
      }
    ]

@Pet3ris
Copy link

Pet3ris commented Mar 30, 2021

I'm still experiencing this issue with browser-fs-access (more details here: GoogleChromeLabs/browser-fs-access#42).

I tried the above solutions without success:

"transformIgnorePatterns": [
  "node_modules/(?!browser-fs-access).+(js|jsx|mjs|ts)$"
]

@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 10, 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