typescript Angular 测试点击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45544167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular testing click event
提问by Stefan
At the moment I'm trying to learn more about testing in Angular (v2+), but I'm stuck at testing click events in a *ngFor loop.
目前,我正在尝试了解更多关于在 Angular (v2+) 中进行测试的信息,但我一直坚持在 *ngFor 循环中测试点击事件。
This is the HTML-code:
这是 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>
This is the onSelect event:
这是 onSelect 事件:
onSelect(hero:Hero):void{
this.selectedHero = hero;
}
I have two questions:
我有两个问题:
- How to write a test that checks if the click event works?
- How to write a test that makes the div element visible when the variable selectedHero is set?
- 如何编写一个测试来检查点击事件是否有效?
- 设置变量 selectedHero 时,如何编写使 div 元素可见的测试?
Thanks in advance!
提前致谢!
UpdateI wrote the following test to check the click event:
更新我编写了以下测试来检查点击事件:
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();
});
});
回答by Max Koretskyi
First, follow this guideon Angular testing to learn what comp
, fixture
and el
variables are.
首先,按照这个关于 Angular 测试的指南来了解什么是comp
,fixture
和el
变量。
How to write a test that checks if the click event works?
如何编写一个测试来检查点击事件是否有效?
You need to spy on onSelect
method and ensure it was triggered:
您需要监视onSelect
方法并确保它被触发:
it('should test click', () => {
spyOn(comp, 'onSelect');
el = fixture.debugElement.query(By.css('li')).nativeElement.click();
expect(comp.onSelect).toHaveBeenCalled();
});
How to write a test that makes the div element visible when the variable selectedHero is set?
设置变量 selectedHero 时,如何编写使 div 元素可见的测试?
You need to test that the class is applied to the element:
您需要测试该类是否应用于元素:
it('should test selected', () => {
el = fixture.debugElement.query(By.css('li')).nativeElement;
expect(el.classList.has('selected')).toBe(false);
comp.onSelect(heroes[0]);
expect(el.classList.has('selected')).toBe(true);
});