Angular怎麼進行單元測試?以下這篇給大家整理分享4個Angular單元測驗寫的高階技巧,希望對大家有幫助!
測試想法:
測試難度,也是逐漸加大的,耗費的時間也是越多的。那麼想測試的簡單,那麼在開發的時候,就有意識的,去把思路理清楚,code寫的簡單高效些~。
本文所使用的測試技術堆疊:Angular12 Jasmine, 雖然其他測試技術語法不同,但整體思路差不多。 【相關教學推薦:《angular教學》】
Tips: Jasmine 測試案例判定,方法有哪些,可以在這裡找到,戳我
其中component,預設是Angular使用以下語法建立的待測試物件的instance
beforeEach(() => { fixture = TestBed.createComponent(BannerComponent); component = fixture.componentInstance; fixture.detectChanges(); });
1.函數調用,且沒有返回值
function test(index:number ,fn:Function){ if(fn){ fn(index); } }
請問如何測試?
反例:直接測試回傳值undefined
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(); })
結構指令,常用語隱藏、顯示、for迴圈展示這類功能
# code @Directive({ selector: '[ImageURlError]' }) export class ImageUrlErrorDirective implements OnChanges { constructor(private el: ElementRef) {} @HostListener('error') public error() { this.el.nativeElement.style.display = 'none'; } }
如何測試?
測試想法:
#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()方法就会被执行到 });
angular中public修飾的,spec.ts是可以存取;但是private,protected修飾的,則不可以;
敲黑板
click事件的觸發,直接js呼叫click,也有模仿滑鼠觸發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>`
如何測試?
測試想法:
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); });
其餘click 參考思路:
思路一:
triggerEventHandler('click');
程式設計影片! !
以上是4個Angular單元測試寫的小技巧,快來看看!的詳細內容。更多資訊請關注PHP中文網其他相關文章!