【问题标题】:How to actually trigger a click event and check the outcome in Angular2如何实际触发点击事件并检查Angular2中的结果
【发布时间】:2017-06-18 15:13:15
【问题描述】:

我想实际检查一下,selected 属性已被呈现为 true 而不是 undefined。

我的工作(手动测试)组件功能:

export class PlayerSelectorComponent implements OnInit {

    players: any = []

    ...

    toggleSelectPlayer( player: any ) {
        if (player.selected) {
            player.selected = false
        }
        else {
            player.selected = true
        }
    }

}

这是模板:

 <ul class="list-group">
     <player-row *ngFor="let player of players"
                 [player]="player"
                 [selected]="player.selected"
                 (click) = "toggleSelectPlayer(player)">
     </player-row>
 </ul>

这里是测试代码:

it( 'should render a player as selected after a user clicks on the player row', fakeAsync( () => {
    let player = fixture.debugElement.query( By.css( '.player-row' ) )
    expect( player.attributes.selected ).toBe( undefined )
    player.triggerEventHandler( 'click', null )
    tick()
    fixture.detectChanges()
    player = fixture.debugElement.query( By.css( '.player-row' ) )
    expect( player.attributes.selected ).toBeTruthy() // Expected undefined to be truthy
} ) )

在代码的最后一行,您可以看到,我的测试没有检测到 player.attributes.selected 在点击后实际上发生了变化。它仍然是未定义的..

【问题讨论】:

  • 问题是什么?
  • 抱歉,更新了问题

标签: angular angular2-testing


【解决方案1】:

问题是您正在查询 css,但实际上并未在您发布的任何内容中操作 css。您想测试组件变量为true。

在你fixture.detectChanges() 之后,你会想要expect( component.player.selected ).toBeTruthy()。这是假设您有一个用于测试的 TestBed。

如果您希望实际检查引导表单组中的“激活”状态(未选中),则需要在 *ngFor 循环中应用 [ngClass]="{'selected':player.selected}"。

【讨论】:

  • 绝对完美的人,测试通过 :) 所以这需要我改变我的心态——自定义输入属性不是我在 DOM 中创建的属性,而是我需要掌握的一些 Angular 2 内部的东西:)
猜你喜欢
  • 2018-11-23
  • 2017-12-15
  • 2019-09-29
  • 1970-01-01
  • 2018-06-03
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
相关资源
最近更新 更多