vendredi 15 février 2019

Testing ngForm form of Angular

I have a Login page form like below -

<form class="login-form" #loginForm="ngForm">  
  <input [(ngModel)]="login.username" required="true" type="text" id="username" name="username"/>
  <button [disabled]="!loginForm.form.valid" label="Login" class="btn-login" type="submit">Login</button>
</form>

Now the test case for checking the disabled/enabled status of Login button -

describe('Login button status', () => {
  let loginBtn, userInputElm;
  beforeEach(() => {
    loginBtn = fixture.nativeElement.querySelector('.btn-login');
    userInputElm = fixture.nativeElement.querySelector('input#username');
    fixture.detectChanges();
  });

  it('should be enabled if "username" is provided', fakeAsync(() => {
    userInputElm.value = 'validusername';
    // component.login.username = 'validuser'; <-- also tried this
    fixture.detectChanges();
    tick(100);
    // button should be enabled
    expect(loginBtn.disabled).toBe(false); <-- Button still remains disabled
  }));
});

As, the angular is not getting notified of changes of #username field, it is not changing status of the Login button. What I can do to succesfully test this?

I have already imported the FormsModule in the TestBed configuration module.

I know I can do things in Angular way using Angular FormGroup, but I would like to keep the form as it is if possible.

Aucun commentaire:

Enregistrer un commentaire