大佬教程收集整理的这篇文章主要介绍了Angular2 之 单元测试,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
Angular的测试工具类包含了TESTBed
类和一些辅助函数方法,当时这不是唯一的,你可以不依赖Angular 的DI(依赖注入)系统,自己new出来测试类的实例。
describe('service: base-data-remote',() => {
let service = new BaseDataRemoteservice();
it('should be created',() => {
expect(servicE).toBeTruthy();
});
});
测试工具包含了TESTBed
类和@angular/core/tesTing
中的一些方法。
TESTBed
将自己重设为初始状态。import { Component } from '@angular/core';
@Component({
@H_419_56@SELEctor: 'app-bAnner',@H_419_56@template: '<h1>{{titlE}}</h1>'
})
export class BAnnerComponent {
title = 'Test Tour of Heroes';
}
let @H_419_56@comp: BAnnerComponent;
let @H_419_56@fixture: ComponentFixture<BAnnerComponent>;
let @H_419_56@de: DebugElement;
let @H_419_56@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; });
注入了真是的服务,并使用Jasmine的spy
替换关键的getXxxx
方法。
spy = spyOn(remoteservice,'getTodos').and.returnValues([Promise.resolve(datas),Promise.resolve(datas2)]);
Spy
的设计是,所有调用getTodos
的方法都会受到立刻解析的承诺,得到一条预设的名言。
写单元测试时,it里经常会有几个常见的方法,async()
,fakeAsync()
,tick()
,jasmine.done()
方法等。
这几个方法,都帮助我们简化了异步测试程序的代码。但是需要正确的使用这几个方法。
组件
@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的调用,因为异步方法TESTBed.compileComponents而变得必要。
测试前期代码
// 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)赋值给组件的hero
属性的。
// 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()通知组件的SELEcted属性发出hero对象,测试程序通过订阅SELEcted事件而检测到这个值,所以测试应该成功。
triggerEventHandler
Angular的DebugElement.triggerEventHandler可以用事件的名字触发任何数据绑定事件。 第二个参数是传递给事件处理器的事件对象。
以上是大佬教程为你收集整理的Angular2 之 单元测试全部内容,希望文章能够帮你解决Angular2 之 单元测试所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。