使用Jest进行测试Vue失败,Jest遇到意外的令牌,SyntaxError:意外的令牌导入

时间:2018-08-31 03:08:43

标签: javascript unit-testing vue.js jestjs

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

  

Jest遇到意外的令牌和SyntaxError:意外的令牌导入

这是我的jest.conf.js,我使用babel-jest和vue jest设置了“ transorm”选项,但仍然收到错误消息,指出无法转换es6语法

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"
            }
          }
        ]
      ]
    }
  }
}

2 个答案:

答案 0 :(得分:1)

很可能在更新程序包依赖项时,"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

答案 1 :(得分:0)

我遇到了类似的问题,“ babel-plugin-transform-es2015-modules-commonjs”正在为我工​​作

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

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