【问题标题】:Angular testing click event角度测试点击事件
【发布时间】:2017-08-07 09:56:25
【问题描述】:

目前我正在尝试了解有关在 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;
}

我有两个问题:

  1. 如何编写一个测试来检查点击事件是否有效?
  2. 如何编写一个测试,在设置变量 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();
  });
});

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    首先,在 Angular 测试中关注 this guide,了解 compfixtureel 变量是什么。

    如何编写一个测试来检查点击事件是否有效?

    您需要监视onSelect 方法并确保它被触发:

    it('should test click', () => {
        spyOn(comp, 'onSelect');
        el = fixture.debugElement.query(By.css('li')).nativeElement.click();
        expect(comp.onSelect).toHaveBeenCalled();
    });
    

    如何编写一个测试,使 div 元素在 变量 selectedHero 是否设置?

    您需要测试该类是否应用于元素:

    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);
    });
    

    【讨论】:

    • 感谢您将我推向正确的方向!我对您的代码进行了一些更改,现在它就像一个魅力:)
    • 太棒了)如果有帮助,您可以接受或支持我的回答)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 2016-01-27
    • 2018-06-12
    • 2021-08-23
    相关资源
    最近更新 更多