
測試想法:
測試難度,也是逐漸加大的,耗費的時間也是越多的。那麼想測試的簡單,那麼在開發的時候,就有意識的,去把思路理清楚,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 參考想法:
思路一:
想法二:
直接測試元件,不利用Host
然後利用fixture.nativeElement.querySelector('.card'),找到綁定click元素;
使用triggerEventHandler('click');