0

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

运行 'vue create' 后,我手动选择了以下选项:TS、Router、Vuex、Linter、Unit、E2E,类样式组件语法:yes,Babel:no,历史模式:no,linter:TSLint,Lint on save ,单元测试解决方案:Mocha,E2E 测试解决方案 Cypress,配置文件:专用文件在此处输入图像描述

'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,而且我认为它不应该是),但我只是收到一条错误消息,指出 perf_hooks 是'在 \node_modules\mocha-webpack\lib 中找不到。

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

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

4

2 回答 2

1

如果除了上述选项之外,我还选择将 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"
  }
}
于 2019-03-20T14:39:38.533 回答
0

你必须伪造 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
          })
        } 
    },  
        
    
  };


于 2020-12-17T10:10:44.390 回答