简体   繁体   中英

Jest: Test suite failed to run, Unexpected token =

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
  }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM