开玩笑:测试套件未能 运行,意外的令牌 =

Jest: Test suite failed to run, Unexpected token =

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

您错过了 babel-preset-stage-0 包裹。

  1. 加上:yarn add babel-preset-stage-0 --dev

  2. 编辑您的 .babelrc{ "presets": ["es2015", "react", "babel-preset-stage-0"] }