我正在尝试使用 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"]
}
包.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
}