我正在尝试使用Jest / Enzyme测试React组件。我希望测试至少可以运行,但是在导入文件时它已经失败并且没有进入测试本身。所以我想知道配置中缺少什么?
错误:
__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 |
测试文件:
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"
}
}
更新:
当我将函数的声明从胖箭头更改为函数关键字时,测试运行。我想知道为什么?
与Jest不兼容的胖箭头功能:
// Favorite.js
isFavorite = (props) => {
return localStorage.getItem(props.recipe.id) ? true : false
}
与Jest合作的函数关键字:
// Favorite.js
isFavorite(props) {
return localStorage.getItem(props.recipe.id) ? true : false
}
答案 0 :(得分:4)
您错过了babel-preset-stage-0
套餐。
添加:yarn add babel-preset-stage-0 --dev
修改您的.babelrc
:{ "presets": ["es2015", "react", "babel-preset-stage-0"] }