Sujit Kumar Singh
Sujit Kumar Singh

Reputation: 1088

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', () => {
    userInputElm.value = 'validusername';
    // component.login.username = 'validuser'; <-- also tried this
    fixture.detectChanges();
    // loginBtn = fixture.nativeElement.querySelector('.btn-login'); <-- tried this (same result)
    // 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? Need to notify Angular about changes.

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.

Upvotes: 1

Views: 772

Answers (1)

Amit Chigadani
Amit Chigadani

Reputation: 29715

Give this a try. You should trigger the change event programmatically on the input field.

it('should be enabled if "username" is provided', () => {
    userInputElm.value = 'validusername';
    userInputElm.dispatchEvent(new Event('input'));
    fixture.detectChanges();

    // button should be enabled
    expect(loginBtn.disabled).toBe(false);
});

Upvotes: 1

Related Questions