如何实际触发click事件并检查Angular2中的结果

时间:2017-06-18 15:13:15

标签: angular angular2-testing

我想实际检查一下,选中的属性是使用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
} ) )

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

1 个答案:

答案 0 :(得分:1)

问题是你在查询css,但实际上并没有在你发布的任何内容中操纵css。您希望将组件变量测试为true

在您fixture.detectChanges()后,您将要expect( component.player.selected ).toBeTruthy()。假设您有一个TestBed用于测试。

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