在升级到Angular 11之前,我通过以下命令对单元测试进行了代码覆盖:
ng test --project my-app --code-coverage true
当我将项目升级到Angular 11时,我仍然可以进行代码覆盖率测试,但是我开始收到一条消息,指出“自11版以来,'karma-coverage-istanbul-reporter'的用法已被弃用”。它要求我安装karma-coverage并更新karma.conf.js。所以我按照它的要求做了。我通过以下命令安装了karma-coverage和karma:npm install karma karma-coverage --save-dev
结果,我在我的package.json中的devDependencies下看到了 karma 的条目:"karma": "^5.2.3",<br>
"karma-coverage": "^2.0.3"
我更新了karma.conf.js文件。以下是存在的内容,除了我的评论之外,所有内容均与原来一样:module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage'), // NEWLY ADDED
// ORIGINALLY HERE NOW REMOVED require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
reporters: ['progress', 'kjhtml', 'coverage'],
// coverageIstanbulReporter NO LONGER HERE
//coverageIstanbulReporter: {
// dir: require('path').join(__dirname, '../../coverage/my-app'),
// reports: ['html', 'lcovonly', 'text-summary'],
// fixWebpackSourcePaths: true
//},
// coverReporter NEWLY ADDED
coverageReporter: {
dir: 'build/reports/coverage',
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'lcov', subdir: 'report-lcov' }
]
},
// THE FOLLOWING REMAINED AS IS
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
完成此更新后,发生了两件事,我不知道为什么。要使警告静音,请在配置文件中为C:/Angular/my-project/projects/my-app/src/app/app.component.spec.ts指定一个有效的类型。 ?
编辑:我找到了答案。在coverageReporter对象内部,您需要将fixWebpackSourcePaths属性添加为true:
coverageReporter: {
dir: 'build/reports/coverage',
reporters: [
{ type: 'html', subdir: 'report-html' },
{ type: 'lcov', subdir: 'report-lcov' }
],
fixWebpackSourcePaths: true
},
最佳答案
我的诀窍是从记者那里删除'coverage'
。应该只是:
reporters: ['progress', 'kjhtml'],
然后按预期创建覆盖率报告,而不会引发奇怪的警告。这似乎是Angular的方式,看看
karma.conf.js
generated by the ng new
schematics。
关于unit-testing - Angular 11单元测试代码覆盖率现已突破,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64810302/