问题
I am trying to test a React component with Jest/Enzyme. I expect the test to at least run, but it already fails when it is importing files and does not get to the test itself. So I am wondering what in the configuration I am missing?
Error:
__tests__/Favorite.test.js
● Test suite failed to run
/src/components/favorite/Favorite.js: Unexpected token (13:13)
11 | }
12 |
> 13 | isFavorite = (props) => {
| ^
14 | return localStorage.getItem(props.recipe.id) ? true : false
15 | }
16 |
Test File:
import React from 'react'
import { mount } from 'enzyme'
import Favorite from '../src/components/favorite/Favorite'
describe('Favorite', () => {
const recipe = {id: "12345"}
const favorite = mount(<Favorite recipe={recipe}/>)
// assertions
})
.babelrc:
{
"presets": ["es2015", "react"]
}
package.json:
"devDependencies": {
"babel-jest": "^21.2.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"enzyme": "^3.2.0",
"enzyme-adapter-react-16": "^1.1.0",
"enzyme-to-json": "^3.2.2",
"jest": "^21.2.1",
"react-test-renderer": "^16.1.1"
},
"jest": {
"setupTestFrameworkScriptFile": "./src/setupTests.js",
"moduleNameMapper": {
"\\.(css|jpg|png|svg|ico)$": "<rootDir>/empty-module.js"
}
}
Update:
When I change the declaration of the functions from fat arrow to function keyword, the tests run. I wonder why?
Fat arrow function that does not work with Jest:
// Favorite.js
isFavorite = (props) => {
return localStorage.getItem(props.recipe.id) ? true : false
}
Function keyword that does work with Jest:
// Favorite.js
isFavorite(props) {
return localStorage.getItem(props.recipe.id) ? true : false
}
回答1:
You missed the babel-preset-stage-0
package.
Add it:
yarn add babel-preset-stage-0 --dev
Edit your
.babelrc
:{ "presets": ["es2015", "react", "babel-preset-stage-0"] }
来源:https://stackoverflow.com/questions/47349190/jest-test-suite-failed-to-run-unexpected-token