![](/img/trans.png)
[英]Unit testing a Service method subscribed to an Observable in Angular
[英]angular unit testing a method having a cont and a for loop
我正在使用 jasmine 在 Angular 中進行單元測試。 我有一個包含const
和for
循環的方法。 下面是代碼:
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.