我很难用Jest设置Vue CLI 3来显示测试范围。我已尽一切可能使它正常工作,但仍未显示任何内容:

Ran all test suites.
----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |        0 |        0 |        0 |        0 |                   |
----------|----------|----------|----------|----------|-------------------|

=============================== Coverage summary ===============================
Statements   : Unknown% ( 0/0 )
Branches     : Unknown% ( 0/0 )
Functions    : Unknown% ( 0/0 )
Lines        : Unknown% ( 0/0 )

以下是我的配置摘录:

jest.config.js:

module.exports = {
  moduleFileExtensions: [
    'js',
    'jsx',
    'json',
    'vue'
  ],
  transform: {
    '^.+\\.vue$': 'vue-jest',
    '.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$': 'jest-transform-stub',
    '^.+\\.jsx?$': 'babel-jest'
  },
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
  },
  snapshotSerializers: [
    'jest-serializer-vue'
  ],
  testMatch: [
    '**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
  ],
  transformIgnorePatterns: ['<rootDir>/node_modules/'],
  testURL: 'http://localhost/'
}

package.json:
....
"scripts": {
  "test:unit": "nyc vue-cli-service test:unit"
},
"nyc": {
  "check-coverage": true,
  "per-file": true,
  "lines": 90,
  "statements": 90,
  "functions": 90,
  "branches": 90,
  "include": [
    "src/**/*.{js,vue}"
  ],
  "exclude": [
    "src/*.js"
  ],
  "reporter": [
    "lcov",
    "text",
    "text-summary"
  ],
  "extension": [
    ".js",
    ".vue"
  ],
  "verbose": true,
  "cache": true,
  "all": true
}

如何正确配置Vue CLI 3和Jest以显示测试覆盖率?

最佳答案

Jest有自己的覆盖工具,因此请从package.json中删除nyc:

"scripts": {
  // "test:unit": "nyc vue-cli-service test:unit" // DELETE
  "test:unit": "vue-cli-service test:unit"
},
// "nyc": {...} // DELETE

要启用Jest的覆盖范围,请在jest.config.js中(根据 collectCoverage )设置 collectCoverageFrom vue-test-utils docs:
collectCoverage: true,
collectCoverageFrom: [
  'src/**/*.{js,vue}',
  '!src/main.js', // No need to cover bootstrap file
],

运行yarn test:unit应该产生如下控制台输出:

vue.js - 如何使用jest使测试覆盖率显示Vue-cli 3中的所有vue文件-LMLPHP

GitHub demo

还要注意,Jest控制台输出仅列出包含可执行JavaScript(Vue SFC的methods)的文件。如果您正在使用默认的Vue CLI生成的模板,则HelloWorld.vue不包含methods,因此不会列出。在上面的屏幕截图中,我向HelloWorld.vue添加了一个未使用的方法,以演示Jest的未发现行报告。

关于vue.js - 如何使用jest使测试覆盖率显示Vue-cli 3中的所有vue文件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53249858/

10-11 11:37
查看更多