angular2 testing - 输入文本更改不会影响ngmodel

时间:2017-01-27 12:38:43

标签: angular

我试图通过angular2 test设置DOM输入元素。:

以下是HTML代码:

<div>
            <label for="Player X">Player X</label>
            <input type="text" id="playerX" required [(ngModel)]="players[0].id" name="playerXid">
        </div>
        <div>
            <label for="Player O">Player O</label>
            <input type="text" id="playerO" required [(ngModel)]="players[1].id" name="playerOid">
        </div>

以下是测试代码,因为players[0].idplayers[1].id为空而失败:

it('Test input <-> player bindings', () => {
        fixture.detectChanges();

        let playerX = fixture.debugElement.nativeElement.querySelector('#playerX');
        playerX.value = 'First';
        playerX.dispatchEvent(new Event('input'));
        let playerO = fixture.debugElement.nativeElement.querySelector('#playerO');
        playerO.value = 'Second';
        playerO.dispatchEvent(new Event('input'));

        fixture.detectChanges();

        expect(comp.players[0].id).toBe('First');
        expect(comp.players[1].id).toBe('Second');
     });

我在这里缺少什么?

更新

我意识到输入值会更新。 问题是comp.players没有!

1 个答案:

答案 0 :(得分:0)

试试这个:

let compiled = fixture.debugElement.nativeElement;
let playerX = compiled.querySelector('#playerX');
let player0 = compiled.querySelector('#playerX');

fixture.detectChanges();

// Change value
playerX.value = 'First';
player0.value = 'Second';

// dispatch input event
dispatchEvent(playerX, 'input');
dispatchEvent(player0, 'input');

让我知道......