要解决Angular 2单元测试的问题,可以按照以下步骤进行:
安装所需的依赖项:
npm install --save-dev karma jasmine @types/jasmine karma-jasmine karma-chrome-launcher karma-coverage-istanbul-reporter
创建一个karma配置文件karma.conf.js
,并配置所需的文件和插件:
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular/cli'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-coverage-istanbul-reporter'),
require('@angular/cli/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
reports: ['html', 'lcovonly'],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
reporters: ['progress', 'kjhtml', 'coverage-istanbul'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
创建一个测试文件,例如app.component.spec.ts
,并编写测试代码:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [AppComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create the app', () => {
expect(component).toBeTruthy();
});
it(`should have as title 'app'`, () => {
expect(component.title).toEqual('app');
});
it('should render title in a h1 tag', () => {
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');
});
});
在package.json
文件中,添加一个test
脚本来运行测试:
"scripts": {
"test": "ng test"
}
运行测试:
npm test
这样,你就可以运行Angular 2的单元测试,并查看测试结果。