How to actually trigger a click event and check th

2019-09-14 16:03发布

问题:

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.