笑话无法测试React状态

时间:2018-10-28 09:06:56

标签: reactjs jestjs

当我向组件添加状态时,我开玩笑的测试失败。 我正在努力取得进展,没有状态就一切正常,因此我认为阅读最新状态声明状态时会出现问题。 我想我缺少某种Babel库或其他东西。

笑话:

这通常意味着您试图导入Jest无法导入的文件     解析,例如这不是普通的JavaScript。           默认情况下,如果Jest看到Babel配置,它将使用该配置来转换您     r个文件,忽略“ node_modules”。           您可以执行以下操作:             要转换某些“ node_modules”文件,可以指定一个      配置中的自定义“ transformIgnorePatterns”。             如果您需要自定义转换,请在您的      配置。             如果您只想模拟非JS模块(例如二进制资产),则可以     可以使用“ moduleNameMapper”配置选项将其存根。           您可以在文档中找到更多详细信息和这些配置选项的示例:https://jestjs.io/docs/en/configuration.html

控制台:

> test@0.1.0 test C:\test
> jest

 FAIL  src/App.test.js
  ? Test suite failed to run

    C:/test/src/App.js: Unexpected token (5:6)

      Jest encountered an unexpected token

      Details:
        3 |
        4 | class App extends Component {
      > 5 |     state={
          |          ^
        6 |             value: 'value'
        7 |     }
        8 |   render() {

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        8.307s
Ran all test suites.
npm ERR! Test failed.  See above for more details.

package.json

{
  "name": "boilertest",
  "version": "0.1.0",
  "private": true,
  "babel": {
    "presets": [
      "es2015",
      "react"
    ]
  },
  "jest": {
    "snapshotSerializers": [
      "<rootDir>/node_modules/enzyme-to-json/serializer"
    ],
    "moduleNameMapper": {
      "^.+\\.(css|scss)$": "identity-obj-proxy"
    }
  },
  "dependencies": {
    "axios": "^0.18.0",
    "bootstrap": "^4.1.3",
    "react": "^16.6.0",
    "react-dom": "^16.6.0",
    "react-router-dom": "^4.3.1",
    "react-scripts": "2.0.5"
  },
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-jest": "^23.6.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "enzyme": "^3.7.0",
    "enzyme-adapter-react-16": "^1.6.0",
    "enzyme-to-json": "^3.3.4",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^23.6.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "jest --watch",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

谢谢!

2 个答案:

答案 0 :(得分:1)

看起来您只需要安装https://www.npmjs.com/package/babel-plugin-transform-class-properties

这样定义状态对象不在当前标准中,这将为您转换它!

答案 1 :(得分:0)

您需要添加danmakenoise建议的内容npm i babel-plugin-transform-class-properties --save。在运行Jest之前,此插件将实验性state = {}转换为constructor(){}语法。

添加此插件后,需要更新.babelrc文件以包括该插件:"plugins": ["transform-class-properties"]