简体   繁体   English

如何在Angular2中实际触发点击事件并检查结果

[英]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. 我想实际检查一下, 所选属性是用true而不是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. 在代码的最后一行中,您可以看到,我的测试未检测到单击后实际上更改了player.attributes.selected。 It remains to be undefined.. 它仍然是不确定的。

The problem is you're querying css, but not actually manipulating css in anything you posted. 问题是您正在查询CSS,但实际上没有在发布的任何内容中操纵CSS。 You want to test the component variable to be true . 您要测试component变量是否为true

After you fixture.detectChanges() you're going to want to expect( component.player.selected ).toBeTruthy() . 你之后fixture.detectChanges()你要去想expect( component.player.selected ).toBeTruthy() This is assuming you have a TestBed for testing. 这是假设您有用于测试的TestBed。

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. 如果您要实际检查引导表单组上的“已激活”状态(未选中),则需要在*中应用[ngClass]="{'selected':player.selected}" ngFor循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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