How to actually trigger a click event and check the outcome in Angular2

喜欢而已 提交于 2019-12-11 16:43:05

问题


I want to actually check, that the selected attribute has been rendered with a true instead of an undefined.

My working (manually tested) Component functionality:

export class PlayerSelectorComponent implements OnInit {

    players: any = []

    ...

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

}

Here is the template:

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

Here is the test code:

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

In the last line of the code, you can see, that my tests do not detect that the player.attributes.selected is actually changed after the click. It remains to be undefined..


回答1:


The problem is you're querying css, but not actually manipulating css in anything you posted. You want to test the component variable to be true.

After you fixture.detectChanges() you're going to want to expect( component.player.selected ).toBeTruthy(). This is assuming you have a TestBed for testing.

If you're looking to actually check the "activated" status (not selected) on your bootstrap form-group, then you'll need to apply your [ngClass]="{'selected':player.selected}" in your *ngFor loop.



来源:https://stackoverflow.com/questions/44616434/how-to-actually-trigger-a-click-event-and-check-the-outcome-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!