Angular2 之 单元测试
Angular的测试工具Angular的测试工具类包含了 孤立的单元测试describe('Service: base-data-remote',() => {
let service = new BaseDataRemoteService();
it('should be created',() => {
expect(service).toBeTruthy();
});
});
利用Angular测试工具进行测试知识点总结测试工具包含了
测试组件import { Component } from '@angular/core';
@Component({
selector: 'app-banner',template: '<h1>{{title}}</h1>'
})
export class BannerComponent {
title = 'Test Tour of Heroes';
}
let comp: BannerComponent;
let fixture: ComponentFixture<BannerComponent>;
let de: DebugElement;
let el: HTMLElement;
describe('BannerComponent',() => { beforeEach(() => { TestBed.configureTestingModule({ declarations: [ BannerComponent ],// declare the test component }); fixture = TestBed.createComponent(BannerComponent); comp = fixture.componentInstance; // BannerComponent test instance // query for the title <h1> by CSS element selector de = fixture.debugElement.query(By.css('h1')); el = de.nativeElement; }); });
测试有依赖的组件,这个依赖的测试这个依赖的模拟方式有两种:伪造服务实例(提供服务复制品)、刺探真实服务。这两种方式都不错,只需要挑选一种最适合你当前测试文件的测试方式来做最好。 伪造服务实例被测试的组件不一定要注入真正的服务。实际上,服务的复制品(stubs,fakes,spies或者mocks)通常会更加合适。 spec的主要目的是测试组件,而不是服务。真实的服务可能自身有问题。 这个测试套件提供了最小化的UserServiceStub类,用来满足组件和它的测试的需求。 userServiceStub = {
isLoggedIn: true,user: { name: 'Test User'}
};
获取注入的服务 测试程序需要访问被注入到组件中的UserService(stub类)。 Angular的注入系统是层次化的。 可以有很多层注入器,从根TestBed创建的注入器下来贯穿整个组件树。 最安全并总是有效的获取注入服务的方法,是从被测试的组件的注入器获取。 组件注入器是fixture的DebugElement的属性。 出人意料的是,请不要引用测试代码里提供给测试模块的userServiceStub对象。它是行不通的! 被注入组件的userService实例是彻底不一样的对象,是提供的userServiceStub
测试代码 beforeEach(() => { // stub UserService for test purposes userServiceStub = { isLoggedIn: true,user: { name: 'Test User'} }; TestBed.configureTestingModule({ declarations: [ WelcomeComponent ],// 重点 providers: [ {provide: UserService,useValue: userServiceStub } ] }); fixture = TestBed.createComponent(WelcomeComponent); comp = fixture.componentInstance; // UserService from the root injector // 重点 userService = TestBed.get(UserService); // get the "welcome" element by CSS selector (e.g.,by class name) de = fixture.debugElement.query(By.css('.welcome')); el = de.nativeElement; });
刺探(Spy)真实服务注入了真是的服务,并使用Jasmine的 spy = spyOn(remoteService,'getTodos').and.returnValues([Promise.resolve(datas),Promise.resolve(datas2)]);
it方法中的几个函数写单元测试时,it里经常会有几个常见的方法, 组件 @Component({
selector: 'twain-quote',template: '<p class="twain"><i>{{quote}}</i></p>'
})
export class TwainComponent implements OnInit {
intervalId: number;
quote = '...';
constructor(private twainService: TwainService) { }
ngOnInit(): void {
this.twainService.getQuote().then(quote => this.quote = quote);
}
}
使用例子: it('should show quote after getQuote promise (async)',async(() => { fixture.detectChanges(); fixture.whenStable().then(() => { // wait for async getQuote fixture.detectChanges(); // update view with quote expect(el.textContent).toBe(testQuote); }); }));
使用例子 it('should show quote after getQuote promise (fakeAsync)',fakeAsync(() => { fixture.detectChanges(); tick(); // wait for async getQuote fixture.detectChanges(); // update view with quote expect(el.textContent).toBe(testQuote); }));
it('should show quote after getQuote promise (done)',done => {
fixture.detectChanges();
// get the spy promise and wait for it to resolve
spy.calls.mostRecent().returnValue.then(() => { fixture.detectChanges(); // update view with quote expect(el.textContent).toBe(testQuote); done(); }); });
测试有外部模板的组件使用例子 // async beforeEach
beforeEach( async(() => { TestBed.configureTestingModule({ declarations: [ DashboardHeroComponent ],}) .compileComponents(); // compile template and css }));
beforeEach里的async函数注意beforeEach里面对async的调用,因为异步方法TestBed.compileComponents而变得必要。 compileComponents
测试带有inputs和outputs的组件测试前期代码 // async beforeEach
beforeEach( async(() => { TestBed.configureTestingModule({ declarations: [ DashboardHeroComponent ],}) .compileComponents(); // compile template and css })); // synchronous beforeEach beforeEach(() => { fixture = TestBed.createComponent(DashboardHeroComponent); comp = fixture.componentInstance; heroEl = fixture.debugElement.query(By.css('.hero')); // find hero element // pretend that it was wired to something that supplied a hero expectedHero = new Hero(42,'Test Name'); comp.hero = expectedHero; fixture.detectChanges(); // trigger initial data binding });
属性测试代码是将模拟英雄(expectedHero)赋值给组件的 // pretend that it was wired to something that supplied a hero
expectedHero = new Hero(42,'Test Name');
comp.hero = expectedHero;
点击事件it('should raise selected event when clicked',() => { let selectedHero: Hero; comp.selected.subscribe((hero: Hero) => selectedHero = hero); heroEl.triggerEventHandler('click',null); expect(selectedHero).toBe(expectedHero); });
这个组件公开EventEmitter属性。测试程序像宿主组件那样来描述它。 heroEl是个DebugElement,它代表了英雄所在的
。 测试程序用”click”事件名字来调用triggerEventHandler。 调用DashboardHeroComponent.click()时,”click”事件绑定作出响应。
如果组件想期待的那样工作,click()通知组件的selected属性发出hero对象,测试程序通过订阅selected事件而检测到这个值,所以测试应该成功。 triggerEventHandler Angular的DebugElement.triggerEventHandler可以用事件的名字触发任何数据绑定事件。 第二个参数是传递给事件处理器的事件对象。
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |