4个Angular单元测试编写的小技巧,快来看看!
Angular怎么进行单元测试?下面本篇给大家整理分享4个Angular单元测试编写的高阶技巧,希望对大家有所帮助!
测试思路:
- 1.能单元测试,尽量单元测试优先
- 2.不能单元测试,通过封装一层进行测试,譬如把测试的封装到一个组件,但又有弱于集成测试
- 3.集成测试
- 4.E2E 测试
单元测试
beforeEach(() => { fixture = TestBed.createComponent(BannerComponent); component = fixture.componentInstance; fixture.detectChanges(); });
函数测试
1.函数调用,且没有返回值
function test(index:number ,fn:Function){ if(fn){ fn(index); } }
请问如何测试?
const res = component.test(1,() => {})); expect(res).tobeUndefined();
# 利用Jasmine it('should get correct data when call test',() =>{ const param = { fn:() => {} } spyOn(param,'fn') component.test(1,param.fn); expect(param.fn).toHaveBeenCalled(); })
结构指令HostListener测试
# code @Directive({ selector: '[ImageURlError]' }) export class ImageUrlErrorDirective implements OnChanges { constructor(private el: ElementRef) {} @HostListener('error') public error() { this.el.nativeElement.style.display = 'none'; } }
如何测试?
- 图片加载错误,才触发,那么想办法触发下错误即可
- 指令一般都依附在组件上使用,在组件image元素上,dispath下errorEvent即可
#1.添加一个自定义组件, 并添加上自定义指令 @Component({ template: `<div> <image src="https://xxx.ss.png" ImageURlError></image> </div>` }) class TestHostComponent { } #2.把自定义组件视图实例化,并派发errorEvent beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ TestHostComponent, ImageURlError ] }); })); beforeEach(() => { fixture = TestBed.createComponent(TestHostComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should allow numbers only', () => { const event = new ErrorEvent('error', {} as any); const image = fixture.debugElement.query(By.directive(ImageURlError)); image.nativeElement.dispatchEvent(event); //派发事件即可,此时error()方法就会被执行到 });
善用 public,private,protected 修饰符
- 如果打算走单元测试,一个个方法测试,那么请合理使用public --- 难度 *
- 如果不打算一个个方法的进行测试,那么可以通过组织数据,调用入口,把方法通过集成测试 -- 难度 ***
测试click 事件
# xx.component.ts @Component({ selecotr: 'dashboard-hero-list' }) class DashBoardHeroComponent { public cards = [{ click: () => { ..... } }] } # html <dashboard-hero-list [cards]="cards" class="card"> </dashboard-hero-list>`
如何测试?
- 直接测试组件,不利用Host
- 利用code返回的包含click事件的对象集合,逐个调用click ,这样code coverage 会得到提高
it('should get correct data when call click',() => { const cards = component.cards; cards?.forEach(card => { if(card.click){ card.click(new Event('click')); } }); expect(cards?.length).toBe(1); });
思路一:
- 利用TestHostComponent,包裹一下需要测试的组件
- 然后利用 fixture.nativeElement.querySelector('.card')找到组件上绑定click元素;
- 元素上,触发dispatchEvent,即可 ,
思路二:
直接测试组件,不利用Host
然后利用 fixture.nativeElement.querySelector('.card'),找到绑定click元素;
使用 triggerEventHandler('click');
更多编程相关知识,请访问:编程视频!!