首頁  >  文章  >  web前端  >  4個Angular單元測試寫的小技巧,快來看看!

4個Angular單元測試寫的小技巧,快來看看!

青灯夜游
青灯夜游轉載
2022-08-11 20:22:492253瀏覽

Angular怎麼進行單元測試?以下這篇給大家整理分享4個Angular單元測驗寫的高階技巧,希望對大家有幫助!

4個Angular單元測試寫的小技巧,快來看看!

測試想法:

  • #1.能單元測試,盡量單元測試優先
  • #2 .不能單元測試,透過封裝一層進行測試,譬如把測試的封裝到一個組件,但又有弱於集成測試
  • 3.集成測試
  • #4.E2E 測試

測試難度,也是逐漸加大的,耗費的時間也是越多的。那麼想測試的簡單,那麼在開發的時候,就有意識的,去把思路理清楚,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();
 })

結構指令HostListener測試

結構指令,常用語隱藏、顯示、for迴圈展示這類功能

 # 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 修飾符

angular中public修飾的,spec.ts是可以存取;但是private,protected修飾的,則不可以;

敲黑板

  • 如果打算走單元測試,一個個方法測試,那麼請合理使用public  --- 難度*
  • 如果不打算一個個方法的進行測試,那麼可以透過組織數據,調用入口,把方法通過集成測試-- 難度***

測試click 事件

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>`

如何測試?

測試想法:

  • #直接測試元件,不利用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);
});

其餘click 參考思路:

思路一:

    ##利用TestHostComponent,包裹一下需要測試的元件
  • 然後利用fixture.nativeElement.querySelector('.card')找到元件上綁定click元素;
  • 元素上,觸發dispatchEvent,即可,
思路二:

  • 直接測試元件,不利用Host

  • 然後利用fixture.nativeElement.querySelector(' .card'),找到綁定click元素;

  • 使用

    triggerEventHandler('click');

更多程式相關知識,請造訪:

程式設計影片! !

以上是4個Angular單元測試寫的小技巧,快來看看!的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:juejin.cn。如有侵權,請聯絡admin@php.cn刪除