【问题标题】:Test Vue with Jest fail, Jest encountered an unexpected token, SyntaxError: Unexpected token import用 Jest 测试 Vue 失败,Jest 遇到了意外的令牌,SyntaxError: Unexpected token import
【发布时间】:2019-02-06 01:00:15
【问题描述】:

我开玩笑地测试 Vue 项目,我得到错误的错误说:

Jest 遇到了意外的令牌和 SyntaxError: Unexpected token import

这是我的 jest.conf.js,我用 babel-jest 和 vue jest 设置了“transorm”选项,但我仍然收到错误说 can't transorm the es6 syntax

const path = require('path')

module.exports = {
  rootDir: path.resolve(__dirname, '../../'),
  moduleFileExtensions: [
    'js',
    'json',
    'vue'
  ],
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
  },
  transform: {
    '^.+\\.js$': '<rootDir>/node_modules/babel-jest',
    '.*\\.(vue)$': '<rootDir>/node_modules/vue-jest'
  },
  testPathIgnorePatterns: [
    '<rootDir>/test/e2e'
  ],
  snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'],
  setupFiles: ['<rootDir>/test/unit/setup'],
  coverageDirectory: '<rootDir>/test/unit/coverage',
  collectCoverageFrom: [
    'src/**/*.{js,vue}',
    '!src/main.js',
    '!src/router/index.js',
    '!**/node_modules/**'
  ]
}

这是 .babelrc 配置:

{
  "presets": [
    [
      "env",
      {
        "modules": false,
        "targets": {
          "browsers": [
            "> 1%",
            "last 2 versions",
            "not ie <= 8"
          ]
        }
      }
    ],
    "stage-2"
  ],
  "plugins": [
    "transform-vue-jsx",
    "transform-runtime",
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "~node_modules/modeling-theme-element/lib"
      }
    ]
  ],
  "env": {
    "test": {
      "presets": [
        "env",
        "jest",
        "stage-2"
      ],
      "plugins": [
        [
          "dynamic-import-node",
          {
            "root": [
              "./src"
            ],
            "alias": {
              "@": "./src"
            }
          }
        ]
      ]
    }
  }
}

【问题讨论】:

  • 我相信这是开玩笑的问题。你用的是哪个版本?你能粘贴你的 package.json 吗?

标签: javascript unit-testing vue.js jestjs


【解决方案1】:

我遇到了类似的问题,“babel-plugin-transform-es2015-modules-commonjs”对我有用

npm i -D babel-plugin-transform-es2015-modules-commonjs

.babelrc 配置 "plugins":["transform-es2015-modules-commonjs"]

【讨论】:

  • 谢谢!我花了 3 周的时间才找到您的解决方案。它对我有用。
【解决方案2】:

很可能在更新包依赖项时,"babel-core" 依赖项可能已更新为 6.xx.x,它应该是 "7.0.0-bridge.0" 才能正常工作。

参考: https://github.com/vuejs/vue-cli/issues/1879#issuecomment-412300256 https://github.com/vuejs/vue-cli/issues/1879#issuecomment-435194932

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-24
    • 2017-09-16
    • 2019-10-07
    • 2017-12-28
    • 2022-06-16
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    相关资源
    最近更新 更多