Home > Enterprise >  Unit-Testing Angular-Material mat-form-field input
Unit-Testing Angular-Material mat-form-field input

Time:10-31

I am trying to test a value change in a mat-form-field input. I studied several solutions but i can't get it to work. The actual expect result is : "Expected '' to equal 'Open Travel'." The value is correct stored in the native element but not in component.name. I really hope someone have a solution. I wasted already so much time on this.

This is my test:

 fit('some test definition', () => {
    fixture.whenStable().then(() => {
      expect(component.name).toEqual('');

      let inputName = fixture.debugElement.nativeElement.querySelector('#name');
      
      inputName.focus();
      inputName.value = 'Open Travel';
      inputName.dispatchEvent(new Event('input'));

      expect(component.name).toEqual('Open Travel');
    });
  });

snippet from html:

 <mat-form-field appearance="fill">
      <mat-label>Project Name</mat-label>
      <input id="name" [(ngModel)]="name" matInput>
 </mat-form-field>

CodePudding user response:

ngModelChange event is not triggered when setting the input directly, using triggerEventHandler method to emit ngModelChange event should set the component variable, not sure if this is the best way of doing this but it will work

fit('some test definition', () => {
  expect(component.name).toEqual('');

  let inputName = fixture.debugElement.query(By.css('#name'));

  inputName.nativeElement.focus();
  inputName.nativeElement.value = 'Open Travel';
  inputName.triggerEventHandler('ngModelChange', 'Open Travel');

  expect(component.name).toEqual('Open Travel');
});
  • Related