问题
I am getting the following error whenever I run jest in commandline:
● Test suite failed to run
/Users/<USER>/<Project>/src/login/LoginAPI.js:13
...headers,
^^^
SyntaxError: Unexpected token ...
The code that it breaks on uses ES6 ellipses:
headers: {
...headers
},
This is what my .babelrc file looks like:
{ "presets":["env", "react"] }
And this is what I have in my package.json:
"dependencies": {
"express": "^4.15.4",
"express-healthcheck": "^0.1.0",
"js-cookie": "^2.1.4",
"normalize.css": "^7.0.0",
"query-string": "^5.0.0",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-router-dom": "^4.2.2"
},
"devDependencies": {
"babel-jest": "^21.2.0",
"babel-preset-env": "^1.6.1",
"babel-preset-es2015": "^6.24.1",
"enzyme": "^3.1.0",
"enzyme-adapter-react-15": "^1.0.2",
"jest": "^21.2.1",
"jest-cli": "^21.2.1",
"react-scripts": "1.0.10"
},
"jest": {
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
},
"moduleFileExtensions": ["js"],
"moduleDirectories": [
"node_modules",
"bower_components",
"shared"
],
"testPathIgnorePatterns": [
"/node_modules/",
"/yarn-cache/"
]
}
回答1:
You need to use a specific babel preset for this syntax. Check this preset
npm install --save-dev babel-plugin-transform-object-rest-spread
And then add this to your .babelrc
{
"plugins": ["transform-object-rest-spread"]
}
You might want to add stage-2 as it has more ES6 goodies.
Note: Jest can read your .babelrc file
回答2:
In babel 7,
babel-plugin-transform-object-rest-spread
will report error: SpreadProperty has been renamed to SpreadElement
.
So I use:
npm install --save-dev @babel/plugin-proposal-object-rest-spread
and config .babelrc
{
"plugins": ["@babel/plugin-proposal-object-rest-spread"]
}
回答3:
There are several solutions to this I believe, this GitHub Issue should outline some of them. I would give this a try first:
{
"presets": ["es2015", "stage-3", "react"]
}
来源:https://stackoverflow.com/questions/46893494/jest-error-unexpected-token-es6