簡體   English   中英

angular 單元測試具有cont和for循環的方法

[英]angular unit testing a method having a cont and a for loop

我正在使用 jasmine 在 Angular 中進行單元測試。 我有一個包含constfor循環的方法。 下面是代碼:

private initializeFilterArrays() {
    const today = new Date().getFullYear();
    for (let i = 0; i < 5; i++) {
      this.yearsFilter.push(today - i);
    }
  }

html 用於此:

<button (click)="initializeFilterArrays()" id="init">Filter</button>

規格:

it('clicking on "Filter" should filter', () => {
   const filterBtn = debugElement.query(By.css('#init'));
   filterBtn.triggerEventHandler('click', {});
   ...
}

那么,在測試用例中,我觸發點擊后我應該寫什么,以便執行該方法的所有行? 我想測試所有行是否都已執行。 以及如何使所有行執行? 如果我想要總代碼覆蓋率怎么辦?

您可以斷言yearsFilter實例變量具有適當的長度。

it('clicking on "Filter" should filter', () => {
   const filterBtn = debugElement.query(By.css('#init'));
   filterBtn.triggerEventHandler('click', {});
   expect(component.yearsFilter.length).toBe(/* new length you expect with all the pushes */);
   // you can also do other assertions on the yearsFilter array as well.
   // Edit 
   expect(component.yearsFilter.includes(2021)).toBeTruthy();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM