2017-02-20 105 views
2

检查单选按钮我有角的组件与此HTML:在角单元测试

<div class="row"> 
    <label for="tipo" class="column">Tipo: </label> 
    <div *ngFor="let tipo of tipos" class="column"> 
    <input type="radio" name="tipo" [value]="tipo.id" 
     [(ngModel)]="movimiento.tipo" (ngModelChange)="alCambiarTipo()"> 
    <span class="{{tipo.texto | lowercase}}">{{ tipo.texto }}</span> 
    </div> 
</div> 

它有两个单选按钮,并在改变它触发我的组件的功能。在我的测试中,我想检查第二个单选按钮来测试我的函数被调用。我试过这个代码,但它不工作:

it('should call alCambiarTipo on radio button change',() => { 
    spyOn(component, 'alCambiarTipo').and.callThrough(); 
    let options: DebugElement[] = fixture.debugElement.queryAll(By.css('input[type="radio"]')); 
    let secondOption: HTMLInputElement = options[1].nativeElement; 
    secondOption.checked = true; 
    expect(component.alCambiarTipo).toHaveBeenCalled(); 
}); 

我使用的输入.click()还试图和它也不能正常工作。我能做些什么来触发我的功能?谢谢。

PS:我也尝试改变模型,加入component.movimiento.tipo = 1;并调用fixture.detectChanges(),它也不起作用。

+0

我有一个类似的问题。你有解决这个问题吗? –

回答

2

因为您使用了错误的事件。应该是更改事件。

options[1].triggerEventHandler('change', { target: options[1].nativeElement }); 

你甚至都不需要设置检查