本文介绍了开玩笑:测试套件无法运行,意外令牌=的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Jest / Enzyme测试React组件。我希望测试至少可以运行,但是在导入文件且未进入测试本身时它已经失败。所以我想知道我缺少什么配置?

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?

错误:

__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:

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"
    }
  }


更新:

当我将功能声明从胖箭头更改为function关键字时,将运行测试。我想知道为什么?

When I change the declaration of the functions from fat arrow to function keyword, the tests run. I wonder why?

不适用于Jest的胖箭头功能:

Fat arrow function that does not work with Jest:

// Favorite.js

  isFavorite = (props) => {
    return localStorage.getItem(props.recipe.id) ? true : false
  }

与Jest兼容的功能关键字:

Function keyword that does work with Jest:

// Favorite.js

  isFavorite(props) {
    return localStorage.getItem(props.recipe.id) ? true : false
  }


推荐答案

您错过了 babel-preset-stage-0 软件包。


  1. 添加它: 纱线添加babel-preset-stage-0 --dev

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

这篇关于开玩笑:测试套件无法运行,意外令牌=的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 22:44