【问题标题】:Jest, env preset and stage-0 featuresJest、env 预设和 stage-0 功能
【发布时间】:2017-06-15 22:12:11
【问题描述】:

我正在尝试配置 jest,但面对它无法处理 es6 功能的事实。

为了解决这个问题,我在 package.json 中添加了配置:

"jest": {
    "transform": {
      "^.+\\.jsx?$": "./node_modules/babel-jest"
    },
}

我的 .babelrc 配置:

{
  "presets": [
    "react",
    "es2017",
    "stage-0",
    ["env", {
      "targets": {
        "browsers": ["last 2 versions"]
      },
      "spec": true,
      "modules": false,
      "debug": true
    }],
  ],
  "plugins": [
    ["transform-class-properties", { "spec": true }]
  ]
}

这对我来说看起来很合适,但玩笑无论如何都无法在 import React from 'react'; 上使用 Test suite failed to run 和在道具上运行

class App extends Component {
   static propTypes = {}
}

目前我不知道出了什么问题,但看起来 stage-x 功能不仅在 env 预设中不可用,而且plugins 和其他预设都被忽略了。 但是 webpack 构建包没有任何错误。 所以看起来这是个笑话。

请帮我看看是怎么回事?

=========== 固定配置.babelrc:

{
  "presets": [
    "react",
    "es2015",
    "es2016",
    "es2017",
    "stage-0",
    ["env", {
      "targets": {
        "browsers": ["last 2 versions"]
      },
      "spec": true,
      "modules": false,
      "debug": true
    }],
  ],
  "plugins": [
    ["transform-class-properties", { "spec": true }]
  ]
}

package.json:

  "jest": {
    "moduleNameMapper": {
      "config.env": "<rootDir>/config/application.production.js",
      "^.+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga|po)$": "<rootDir>/__mocks__/fileMock.js",
      "^.+\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
    },
    "moduleFileExtensions": [
      "js",
      "jsx",
      "js",
      "json"
    ]
  },

【问题讨论】:

    标签: javascript reactjs babeljs jestjs babel-jest


    【解决方案1】:

    es2017 预设不包括es2016es2015。 您可以明确包含所有这些,也可以使用 preset-env 代替。

    此外,您不必在 jest 配置中显式设置 transform 属性。

    from Jest documentation:

    注意:安装 Jest 时会自动安装 babel-jest,如果项目中存在 babel 配置,则会自动转换文件。

    【讨论】:

    • 好吧,我已经删除了它,但在 import React from 'react'; 上开玩笑仍然失败
    • 傻我,我怎么会错过它。你应该使用preset-env,因为es2017不包括es2016es2015。我会修复答案
    • 但实际上我在上面的配置中有preset-env...但是看起来你是对的,我已经将配置更改为上面的[package.json]和[.babelrc]。我已将它们放入原始帖子,因为它们不适合评论大小。但我觉得我的 .babelrc 现在有点奇怪。
    猜你喜欢
    • 1970-01-01
    • 2020-05-07
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    相关资源
    最近更新 更多