1
目前我想了解更多關於在Angular(v2 +)中測試的內容,但是我一直在測試* ngFor循環中的單擊事件。角度測試點擊事件
這是HTML代碼:
<div *ngIf="selectedHero">...</div>
<ul class="heroes">
<li *ngFor="let hero of heroes" (click)="onSelect(hero)" [class.selected]="hero === selectedHero">
<span class="badge">{{hero.id}}</span> {{hero.name}}
</li>
</ul>
這是onSelect事件:
onSelect(hero:Hero):void{
this.selectedHero = hero;
}
我有兩個問題:
- 如何寫一個測試,檢查是否點擊事件的作品?
- 如何編寫一個測試,使變量selectedHero被設置時div元素可見?
在此先感謝!
更新 我寫了下面的測試來檢查點擊事件:
it('should trigger a click event',() => {
fixture.detectChanges();
fixture.whenStable().then(() => {
let comp = fixture.componentInstance;
spyOn(comp, 'onSelect');
let el = fixture.debugElement.query(By.css('li')).nativeElement.click();
expect(comp.onSelect).toHaveBeenCalled();
});
});
謝謝你把我推到正確的方向!我對你的代碼做了一些修改,現在它就像一個魅力:) – Stefan
偉大)如果它幫助你可以接受或upvote我的答案) –