【问题标题】:Jest can't test React stateJest 无法测试 React 状态
【发布时间】:2019-04-01 11:09:39
【问题描述】:

当我向组件添加状态时,我的测试失败了。 我试图获得快照,并且没有状态一切正常,所以我认为阅读最新反应声明状态的“风格”存在问题。 我想我错过了某种 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"
  ]
}

谢谢!

【问题讨论】:

    标签: reactjs jestjs


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2017-11-26
        • 2020-01-21
        • 2019-01-28
        • 2020-11-25
        • 1970-01-01
        • 1970-01-01
        • 2015-07-31
        • 2020-04-02
        • 1970-01-01
        相关资源
        最近更新 更多