vue-cli 生成的单元测试抛出异常

Unit-tests produced by vue-cli throw exceptions

使用vue-cli(v3.5.1)创建项目后,当我运行: 'npm run test:unit'时自动创建的单元测试失败。

在运行ning 'vue create'之后,我手动选择了以下选项:TS, Router, Vuex, Linter, Unit, E2E, class-style component syntax: yes, Babel : no, history mode: no, linter: TSLint, Lint on save, unit-test solution: Mocha, E2E test solution Cypress, config files: dedicated files.

'npm run test:unit' 的输出如下。

WEBPACK Compiled successfully in 7321ms
MOCHA Testing...
RUNTIME EXCEPTION Exception occurred while loading your tests
ReferenceError: performance is not defined at Module../node_modules/vue/dist/vue.runtime.esm.js

我试图修改用于 运行 测试的 npm 脚本,如下所示(不确定包含是否来自 Node,我认为不应该),但是我刚收到一条错误消息,指出在 \node_modules\mocha-webpack\lib 中找不到 perf_hooks。

"test:unit": "vue-cli-service test:unit --include perf_hooks"

代码示例: https://github.com/derek-baker/super-duper-guacamole

如果除了上述选项之外,我还选择将 Babel 作为一项功能包括在内,并且还将 Babel 与 TypeScript 一起用于自动检测的 polyfill,则单元测试将按预期运行。工作配置示例如下。

{
  "name": "vue-cli-test",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "test:e2e": "vue-cli-service test:e2e",
    "test:unit": "vue-cli-service test:unit"
  },
  "dependencies": {
    "vue": "^2.6.6",
    "vue-class-component": "^6.0.0",
    "vue-property-decorator": "^7.0.0",
    "vue-router": "^3.0.1",
    "vuex": "^3.0.1"
  },
  "devDependencies": {
    "@types/chai": "^4.1.0",
    "@types/mocha": "^5.2.4",
    "@vue/cli-plugin-babel": "^3.5.0",
    "@vue/cli-plugin-e2e-cypress": "^3.5.0",
    "@vue/cli-plugin-typescript": "^3.5.0",
    "@vue/cli-plugin-unit-mocha": "^3.5.0",
    "@vue/cli-service": "^3.5.0",
    "@vue/test-utils": "1.0.0-beta.29",
    "chai": "^4.1.2",
    "typescript": "^3.2.1",
    "vue-template-compiler": "^2.5.21"
  }
}

你必须伪造isServerBuild 有一个未解决的问题 https://github.com/vuejs/vue-cli/issues/2270#issue-351812395

mocha webpack 参考 https://github.com/vuejs/vue-cli/blob/dev/packages/%40vue/cli-plugin-unit-mocha/index.js#L5

快速补救措施:

// vue.config.js
module.exports = {
    chainWebpack: (config) => {
      if (process.env.NODE_ENV === 'test') {    
        config.merge({
            // target: 'node',
            devtool: 'inline-cheap-module-source-map'
        })
        config.module
        .rule('vue')
          .use('vue-loader')
          .tap(options => {
            options.isServerBuild = false
            return options
          })
        } 
    },  
        
    
  };