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

1

0

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

Redmond answered 18/6, 2017 at 15:13 Comment(2)
What's the question, or problem?Bogusz
sorry, updated the questionRedmond
B
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.

Bogusz answered 18/6, 2017 at 15:37 Comment(1)
Absolutely perfect man, tested passed :) So this requires me to change my mindset - the custom input attributes are not attributes that I create in the DOM, rather some angular 2 inner thingy that I need to grasp :)Redmond

© 2022 - 2024 — McMap. All rights reserved.