要给出Angular和Jasmine的单元测试用例,首先需要安装Jasmine和Karma。以下是一个简单的Angular组件的示例,包含了一些基本的单元测试用例:
首先,安装Jasmine和Karma:
npm install --save-dev jasmine karma karma-jasmine karma-chrome-launcher
接下来,在项目中创建一个组件:
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: '{{ title }}
',
})
export class AppComponent {
title = 'My App';
}
然后,创建一个测试文件:
// app.component.spec.ts
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
let fixture: ComponentFixture;
let component: AppComponent;
beforeEach(async () => {
await 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 render title in h1 tag', () => {
const compiled = fixture.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('My App');
});
});
最后,执行测试:
ng test
这些测试用例会测试AppComponent是否能够成功创建,并且是否能够正确渲染标题。