Unit testing angular forms with Jest

44 Views Asked by At

I am facing issue with htmlelement.dispatchEvent(new Event('input')). It is resetting value of input field and variable associated to ''

unit test code-

it('should call onSubmit method when form is submitted', fakeAsync(() => {
    app.page = 'test1'
    fixture.detectChanges();
    const emailInput: HTMLInputElement = fixture.nativeElement.querySelector('input');
    const newEmail = '[email protected]';
    emailInput.value = newEmail;

    // Trigger an input event to update ngModel
    emailInput.dispatchEvent(new Event('input'));
    fixture.detectChanges();

    console.log("value2", app.details.email, emailInput.value);  //getting empty value in both
    expect(app.details.email).toBe(newEmail); //test fail
  }));

Code-

<form #myForm="ngForm" (ngSubmit)="onSubmit()">
<app-input
        [type]="'email'"
        name="email"
        [formGroup]="myForm"
        [(ngModel)]="details.email"
        label="Email"
        [placeholder]="'Email'"
        required
        pattern=""
        [isEditable]="true"
></app-input>
</form>

app-input->

<div class="l-form-group">
    <label for="" class="form-label l-body" [innerHTML]="label"></label>
    <input
      type="text"
      [id]="name"
      [placeholder]="placeholder"
      [name]="name"
      #temp="ngModel"
      class="form-input l-form-input"
      [(ngModel)]="value"
      [readOnly]="readOnly"
    />
  </div>
0

There are 0 best solutions below