Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check a radio button in an Angular unit test

I have a component in Angular with this 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 has two radio buttons, and on change it triggers a function in my component. In my test I want to check the second radio button to test that my function is called. I've tried this code but It's not working:

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();
});

I've also tried using .click() on the input and it's also not working. What can I do to trigger my function? Thanks.

PS: I've also tried to change the model adding component.movimiento.tipo = 1; and calling fixture.detectChanges() and it's also not working.

like image 845
Elias Garcia Avatar asked Feb 20 '17 12:02

Elias Garcia


2 Answers

The answer from @maxisam is correct, additionally you could use:

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

If you want more compact form :)

like image 35
Jan Kubovy Avatar answered Oct 19 '22 09:10

Jan Kubovy


Because you use a wrong event. It should be change event.

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

You don't even need to set check

like image 173
maxisam Avatar answered Oct 19 '22 08:10

maxisam