Jest导入重新导出的命名导出

时间:2018-02-12 18:01:12

标签: javascript jestjs

我试图测试导入重新导出命名导出的模块。除标题所示的情况外,基本import语句正常工作(默认和命名)。

repro-repo:https://github.com/bali182/babel-jest-export-everything-bug (我认为这对Jest来说是一个问题,但在打开一个issue开发人员后发现这是一个配置问题,所以我在这里问一下)

要在此处演示此问题:

的package.json

{
  "name": "babel-jest-export-everything-bug",
  "scripts": {
    "test": "jest --config .jestrc.json"
  },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-jest": "^21.2.0",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "jest": "^21.2.1"
  }
}

.babelrc

{
  "presets": [
    [ "es2015", { "modules": "commonjs" } ],
    "stage-0",
    "react"
  ],
  "plugins": [
    "transform-decorators-legacy",
    "transform-runtime"
  ]
}

.jestrc.json

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

namedExports.js

export const x = 1
export const y = 2
export const z = 3

reExports.js

export * from './namedExports'
export default { hello: 'world' }

reExports.test.js

import Foo, { x, y, z } from './reExports'

describe('testing re-exports', () => {
  it('will never get to this method', () => {
    expect(x).toBe(1)
  })
})

然后以

失败
SyntaxError: Unexpected token import

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:305:17)
  at Object.<anonymous> (src/reExports.test.js:1:120)
      at Generator.next (<anonymous>)

有什么建议我在这里做错了吗?

1 个答案:

答案 0 :(得分:1)

解决方案

发生这种情况是由于 transform-runtime 插件引起的,为了对其进行修复,只需将您的 .babelrc 文件更新为

["transform-runtime", { "polyfill": false }]

请参阅我的文件示例:

{
  "presets": [
    ["env", {
      "modules": false,
      "targets": {
        "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
      }
    }],
    "stage-2"
  ],
  "plugins": [
    "jsx-vue-functional",
    "transform-vue-jsx", ["transform-runtime", { "polyfill": false }],
    "transform-decorators-legacy",
    "lodash"
  ],
  "env": {
    "test": {
      "presets": ["env", "stage-2"],
      "plugins": [
        "transform-vue-jsx", 
        "transform-es2015-modules-commonjs", 
        "dynamic-import-node",
        "transform-decorators-legacy"
      ]
    },
    "cli": {
      "presets": ["env", "stage-2"],
      "plugins": [
        [ "babel-plugin-webpack-alias", { "config": "./aliases.config.js" } ],
        "transform-vue-jsx", 
        "transform-es2015-modules-commonjs", 
        "dynamic-import-node",
        "transform-decorators-legacy"
      ]
    }
  }
}