在Angular中,可以使用Jasmine和Karma进行测试模块和代码覆盖率的解决方案。下面是一个简单的示例:
npm install --save-dev jasmine karma karma-jasmine karma-chrome-launcher karma-coverage-istanbul-reporter
app.component.spec.ts
:import { TestBed, ComponentFixture } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [AppComponent],
});
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create the app', () => {
expect(component).toBeTruthy();
});
it('should have a title', () => {
expect(component.title).toBeDefined();
});
});
karma.conf.js
文件:module.exports = function(config) {
config.set({
frameworks: ['jasmine'],
files: [
'src/**/*.spec.ts'
],
preprocessors: {
'src/**/*.spec.ts': ['@angular-devkit/build-angular']
},
browsers: ['Chrome'],
reporters: ['progress', 'coverage-istanbul'],
coverageIstanbulReporter: {
dir: require('path').join(__dirname, 'coverage'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
singleRun: true
});
};
ng test
coverage/index.html
文件。以上示例演示了如何测试一个简单的Angular组件并生成代码覆盖率报告。你可以根据自己的需要进行扩展和修改。