Jest: Test suite failed to run, Unexpected token =

我与影子孤独终老i 提交于 2020-01-05 08:39:31

问题


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.

  1. Add it: yarn add babel-preset-stage-0 --dev

  2. Edit your .babelrc: { "presets": ["es2015", "react", "babel-preset-stage-0"] }



来源:https://stackoverflow.com/questions/47349190/jest-test-suite-failed-to-run-unexpected-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!