"unexpected token import" error while running tests - reactjs

when I run the test, I get the following error:
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import React from 'react';
^^^^^^
SyntaxError: Unexpected token import
It makes sense, since all the lines of "import React" or "import Enzyme", are marked as an error by ESlint. I don´t know why.
This is my .babelrc file:
{
"presets": [
"react",
"stage-2",
["env", {
"test": {
"presets": ["env", "react", "stage-2"],
"plugins": ["transform-export-extensions"],
"only": [
"./**/*.js",
"node_modules/jest-runtime"
]
},
"targets": {
"browsers": ["last 2 versions", "safari >= 7"]
},
"modules": false
}]
]
}

If you are using babel 6 and jest 24 then be informed that jest 24 has dropped support for babel 6.
There are two solutions
Upgrade your app to babel 7. (actively maintained by its developers)
If you don't want to upgrade, make sure that you stick on jest 23.
There is one more work around if you want to use jest 24. Use babel-jest locked at version 23.
"dependencies": {
"babel-core": "^6.26.3",
"babel-jest": "^23.6.0",
"babel-preset-env": "^1.7.0",
"jest": "^24.0.0"
}

Hello dev can you try,
install babel-jest
set this inside .babelrc
"env": {
"test": {
"presets": ["es2015", "react"],
"plugins": ["syntax-object-rest-spread", "transform-es2015-modules-commonjs"]
},
testing with jest

Related

support for the experimental 'jsx' isn't currently enabled

So I have endlessly searched the web to fix this issue.
"support for the experimental 'jsx' isn't currently enabled...
Add #babel/preset-react to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add #babel/plugin-syntax-jsx to the 'plugins' section to enable parsing."
So I had tons (like 100) of these as errors, so I altered my .babelrc and .babel.config.js to look like:
{
test: /\.jsx?$/,
exclude: [/node_modules/],
use: [
{
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-env',
'#babel/preset-react',{
'plugins': [
["#babel/plugin-proposal-class-properties", { "loose": true }]
]}]
}
}]}
and the config:
"presets": [
"react",
"#babel/preset-env",
"#babel/preset-typescript",
"#babel/preset-react"
],
"plugins": [
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
],
[
"#babel/plugin-transform-runtime",
{
"regenerator": true
}
]
]
Which resolved most of these errors.
However I keep seeing this same error for 5 files -> there are no noticeable differences between these 5 files and the 100's that were throwing the exact same errors before.
Upon the advice of other stack overflow answers and the internet I changed my .babelrc and config.js:
{
test: /\.jsx?$/,
exclude: [/node_modules/],
use: [
{
loader: 'babel-loader',
options: {
presets: [
'#babel/preset-env',
'#babel/preset-react',
'#babel/preset-typescript',{
'plugins': [
["#babel/plugin-proposal-decorators", { "legacy": true }],
"#babel/plugin-syntax-dynamic-import",
"#babel/plugin-transform-regenerator",
["#babel/plugin-transform-runtime", {helpers: false, regenerator: true}],
["#babel/plugin-proposal-class-properties", { "loose": true }]
]}]
}
}]}
and the config:
"presets": [
"react",
["#babel/preset-env",
{
"targets": {
"esmodules": true,
"node" : "current"
},
}
],
"#babel/preset-typescript",
"#babel/preset-react"
],
"plugins": [
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
],
[
"#babel/plugin-transform-runtime",
{
"regenerator": true
}
]
]
I have tried many different combinations of these packages, adding one each time to see if it would build or change anything and nothing changed. I also tried adding #babel/plugin-syntax-jsx to the plugins, but it didn't seem to work either.
I've also tried having the #babel packages into the .babelrc as well, but that didn't work either.
Is there any other packages I can try to include or use? Or settings for the packages that might change it for these files?
EDIT: package.json dependencies include:
"#babel/runtime": "^7.10.4",
"#babel/cli": "^7.10.4",
"#babel/core": "^7.10.4",
"#babel/plugin-proposal-class-properties": "^7.10.4",
"#babel/plugin-proposal-decorators": "^7.10.4",
"#babel/plugin-syntax-dynamic-import": "^7.8.3",
"#babel/plugin-syntax-jsx": "^7.10.4",
"#babel/plugin-transform-runtime": "^7.10.4",
"#babel/preset-env": "^7.10.4",
"#babel/preset-react": "^7.10.4",
"#babel/preset-typescript": "^7.10.4",
"core-js": "^3.6.5",
"react": "^16.0.0",
"react-dom": "^16.0.0",
Creating a babel.config.js with this script solve my issue
module.exports = {
presets:[
"#babel/preset-env",
"#babel/preset-react"
]
}
I must have tried tons of different ways. Sharing what worked for me. Do take note of the versions, different versions might need tweaks.
My react project was created using create-react-app (CRA). Now since CRA hides babel and webpack config files and there is no way to modify them, there are basically 2 options:
react eject (which I didn't try. Felt managing all by myself could get bit overwhelming).
Use react-app-rewired to tweak babel configs without having to eject. (I used this)
I additionally used customize-cra. React-app-rewired suggests it for later versions of CRA.
Update scripts and add dev dependencies in package.json:
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject",
"docs": "jsdoc -c jsdoc.conf.json"
},
"devDependencies": {
"#babel/plugin-proposal-class-properties": "^7.10.1",
"customize-cra": "^1.0.0",
"react-app-rewired": "^2.1.6",
"#babel/preset-react": "^7.10.1"
}
config-overrides.js (must be at root level, i.e. at same directory level of package.json).
If error is from some library in node_modules, make sure to 'include' it (babelInclude):
const path = require('path');
const {
override,
babelInclude,
addBabelPreset,
addExternalBabelPlugin,
} = require('customize-cra');
module.exports = override(
babelInclude([
path.resolve('src'),
path.resolve('node_modules/react-native-animatable'),
]),
addBabelPreset("#babel/preset-react"),
addExternalBabelPlugin('#babel/plugin-proposal-class-properties'),
);
This is difficult for us backend engineers just starting out with React, iterating on the community's 3 or 4 years' worth of hackish workarounds to fundamental problems with create-react-app. After a whole week of dead-end encounters with deprecated packages and advice, I learned it turns out you don't need react-app-rewired at all.
Here's my answer (hopefully helps others who follow the same google rabbit-hole): define these in your package.json:
"main": "./build/index.js",
"module": "./build/index.js",
"devDependencies": {
"#babel/cli": "^7.14.3",
"#babel/core": "^7.14.3",
"#babel/preset-env": "^7.14.4",
"#babel/preset-react": "^7.13.13",
"commander": "^7.2.0",
...
},
"scripts": {
...
"transpile": "NODE_ENV=production npx babel --out-dir ../build --relative --copy-files src",
},
"babel": {
"presets": [
"#babel/preset-env",
"#babel/preset-react"
]
},
The npm transpile ; npm publish commands should now work. I found that due to the issue described here by Utku Gultopu, users of yarn will need to do this beforehand to fully upgrade from babel 6 to 7:
npm install #babel/core #babel/cli #babel/preset-react #babel/preset-env
You don't need any of these: webpack.config.js, .babelrc or babel.config.js. Be sure to clear the build subdirectory (and include it in .gitignore) before running either the build (for creating a runtime image) or transpile (for publishing your module library) operations--they are two very different things.
Are you running this inside of a node_modules folder? If so you need to change
exclude: [/node_modules/],
so it doesn't exclude your project.
It should become something along the lines of
exclude: [/node_modules/ &&
!/node_modules\/(project_name)/],
But with correct regex syntax and change project_name to the folder name.

Trying to install MobX but getting decorators error when start up the server

When I install Mobx and Mobx react I am getting the following error.
./src/index.js
Error: The 'decorators' plugin requires a 'decoratorsBeforeExport' option,
whose value must be a boolean. If you are migrating from Babylon/Babel 6 or
want to use the old decorators proposal, you should use the 'decorators-legacy'
plugin instead of 'decorators'.
Now I have ejected the dependencies and installed the decorators-legacy as a plugin. This is what I have in my package.json file
"babel": {
"plugins": [
"transform-decorators-legacy"
],
"presets": [
"react-app"
]
},
"devDependencies": {
"#babel/plugin-proposal-decorators": "^7.1.2",
"babel-plugin-transform-decorators-legacy": "^1.3.5"
}
Any help would be appreciated as this has been driving my crazy for the last few days.
As Tholle wrote the link was very helpful. My config in my package.json.
"babel": {
"presets": ["#babel/preset-env","react-app"],
"plugins": [
["#babel/plugin-proposal-decorators", { "legacy": true }],
["#babel/plugin-proposal-class-properties", { "loose": true }]
]
},
"devDependencies": {
"#babel/plugin-proposal-decorators": "^7.1.2",
"babel-plugin-transform-decorators-legacy": "^1.3.5"
}

Cannot find module 'npm:react#16.4.1/index.js' from 'react#16.4.1.js' hen running jest test suite with react

I'm trying to migrate a project from using karma, phantomJs to jest, but I cannot get my config files right. I keep getting the following error:
FAIL test/unit/components/SomethingWentWrong/SomethingWentWrong.spec.js
● Test suite failed to run
Cannot find module 'npm:react#16.4.1/index.js' from 'react#16.4.1.js'
> 1 | module.exports = require("npm:react#16.4.1/index.js");
| ^
at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:221:17)
at Object.<anonymous> (jspm_packages/npm/react#16.4.1.js:1:18)
Here is a snoppet with my babel and jest configuration.
... rest of code
"devDependencies": {
"#babel/core": "^7.0.0-beta.56",
"babel-jest": "^23.4.2",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"jest": "^23.4.2",
"react-test-renderer": "^16.4.2"
},
"jest": {
"verbose": true,
"testURL": "http://localhost/",
"transform": {
"^.+\\.(jsx|js)?$": "<rootDir>/node_modules/babel-jest"
},
"collectCoverageFrom": [ "!**/node_modules/**" ]
},
"babel": {
"presets": [
[
"env",
{
"loose": true,
"debug": false,
"targets": {
"browsers": [
"last 3 versions"
]
}
}
],
"react"
]
}
... rest of code
I actually found out what the problem was, since this project is handling dependencies both with jspm and npm for some reason some packages don't get installed even after doing npm install my_package or jspm install npm:my_package. A quick look at the node_folder confirm that the packages were not installed even though they appeared on the package.json
npm cache verified and a new jspm install npm: my_package solved the issue

jest: Test suite failed to run, SyntaxError: Unexpected token import

This is my jest configuration from the package.json file:
"jest": {
"automock": false,
"browser": true,
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "./app/tests/mocks/FileMock.js",
"\\.(css|less)$": "identity-obj-proxy"
},
"moduleFileExtensions": [
"js",
"jsx"
],
"moduleDirectories": [
"node_modules"
],
"transform": {
"^.+\\.jsx?$": "./node_modules/babel-jest",
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "./app/tests/mocks/FileTransformer.js"
},
"testEnvironment": "jsdom",
"testPathDirs": [
"./app/tests"
],
"testRegex": ".*.test.js",
"verbose": true
}
And the .babelrc file located in my root folder:
{
"plugins": ["syntax-dynamic-import", "transform-runtime"],
"presets": [
[
"es2015",
{
"modules": false
}
],
"react",
"stage-0"
],
"env": {
"start": {
"presets": [
"react-hmre"
]
}
}
}
According to the documentation found at the jest getting started page this is everything I need for babel to work it's magic.
Regardless, this test:
import React from 'react';
import {shallow} from 'enzyme';
import Landing from '../components/Landing.component';
describe('<Landing/>', () => {
it('should render a header to the page', () => {
const landing = shallow(<Landing/>);
expect(landing.find('h1').text()).toBe('This is the Landing component');
});
});
returns:
FAIL app/tests/Landing.component.test.js
● Test suite failed to run
/Users/shooshte/PersonalProjects/surviveJS/app/tests/Landing.component.test.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import React from 'react';
^^^^^^
SyntaxError: Unexpected token import
at transformAndBuildScript (node_modules/jest-runtime/build/transform.js:320:12)
What am I doing wrong?
Jest sets the env variable to test, so I had to add my presets to the env setting in .babelrc:
{
"plugins": ["syntax-dynamic-import", "transform-runtime"],
"presets": [
[
"es2015",
{
"modules": false
}
],
"react",
"stage-0"
],
"env": {
"start": {
"presets": [
"react-hmre"
]
},
"test": {
"presets": ["es2015", "react", "stage-0"]
}
}
}
Each yearly preset only compiles what was ratified in that year. babel-preset-env replaces es2015, es2016, es2017, latest
Based on this, on latest configurations you must use/replace your Plugins/Preset of es2015 and any esX to the new one: env.
You must install babel-preset-env with npm install.
In your .babelrc you should update accordingly:
{
"presets": [
"env",
"stage-0",
"react-native"
],
"plugins": ...
}
More information on Babel plugins official Documentation.
☝️ Remember the order of the plugins/preset in the array is important.
In my case, I had the following .babelrc config:
{
"presets": [
["env", { "modules": false }],
"react",
"stage-2"
],
"plugins": [
"transform-runtime",
"transform-class-properties",
"react-hot-loader/babel"
]
}
Even though babel-env was specified I still got the error. To fix it I had to remove the "modules": false flag.
Jest doesn't handle imports so it needs a transform plugin, and this is why I had to add the plugin:
babel-plugin-dynamic-import-node
and update my babel settings to tell jest to use this plugin to transform the code properly:
"env": {
"test": {
"plugins" : ["dynamic-import-node"]
}
}
GitHub thread
You need to install babel-jest. I had the same problem.
Go to your app directory, yarn add babel-jest
Good luck!
The following .babelrc works for me (without additions):
{
"presets": [["env", {
"debug": false,
"modules": false
}], "es2015", "stage-0", "react"],
"plugins": [
"react-hot-loader/babel",
"syntax-dynamic-import",
"dynamic-import-node",
"transform-class-properties",
"transform-decorators-legacy"
]
}
"devDependencies" section of package.json looks like this:
...
"devDependencies": {
"babel-cli": "latest",
"babel-core": "^6.26.3",
"babel-eslint": "^8.2.3",
"babel-jest": "^22.4.4",
"babel-loader": "latest",
"babel-plugin-dynamic-import-node": "^1.2.0",
"babel-plugin-lodash": "latest",
"babel-plugin-syntax-dynamic-import": "^6.18.0",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-decorators-legacy": "latest",
"babel-plugin-transform-dynamic-import": "^2.0.0",
"babel-plugin-transform-flow-strip-types": "^6.22.0",
"babel-plugin-transform-object-rest-spread": "latest",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-flow": "^6.23.0",
"babel-preset-react": "^6.24.1",
"babel-preset-react-app-babel-7": "^4.0.1",
"babel-preset-stage-0": "^6.24.1",
...

Node app fails with SyntaxError: Unexpected token '...'

Using Babel and Webpack to build a React application.
During the build process, it fails with SyntaxError: Unexpected token ...
Babel 6 introduced a change to no longer transpile ES2015 by default. See more detail here: https://babeljs.io/blog/2015/10/29/6.0.0
To fix this, edit your package.json or .babelrc file to include { "presets": ["es2015"] }
Here's an example of the section of my package.json file with the fix:
"webpack-hot-middleware": "^2.10.0",
"webpack-middleware": "^1.5.1"
},
"babel": {
"presets": [
"react",
"node5",
"stage-0",
"es2015"
],
"env": {
"test": {
"plugins": [
"rewire"
]
}
}
},
"eslintConfig": {

Resources