检查Angular单元测试中的单选按钮

Eli*_*cia 5 unit-testing angular

我在Angular中有一个使用此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>
Run Code Online (Sandbox Code Playgroud)

它有两个单选按钮,在更改时它会在我的组件中触发一个功能.在我的测试中,我想检查第二个单选按钮以测试我的函数被调用.我已经尝试过这段代码,但它不起作用:

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();
});
Run Code Online (Sandbox Code Playgroud)

我也试过使用.click()输入,它也没有用.我该怎么做才能触发我的功能?谢谢.

PS:我也尝试改变模型添加component.movimiento.tipo = 1;和调用fixture.detectChanges(),它也无法正常工作.

Jan*_*ovy 7

@maxisam 的答案是正确的,另外您可以使用:

inputElement.nativeElement.dispatchEvent(new Event('change'));

如果你想要更紧凑的形式:)


max*_*sam 5

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

  options[1].triggerEventHandler('change', { target: options[1].nativeElement });
Run Code Online (Sandbox Code Playgroud)

您甚至不需要设置检查