简体   繁体   中英

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

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..

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM