I have a simple form with 2 input boxes and a submit button.
<div class="login jumbotron center-block">
<h1>Login</h1>
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" formControlName="username" name="username" placeholder="Username" required>
<div *ngIf="formErrors.username" class="alert alert-danger"> {{ formErrors.username }} </div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" formControlName="password" name="password" placeholder="Password" required>
<div *ngIf="formErrors.password" class="alert alert-danger"> {{ formErrors.password }} </div>
</div>
<button type="submit" class="btn btn-default" [disabled]="!loginForm.valid" >Submit</button>
</form>
</div>
Now when the 2 input boxes are empty , the submit button should be disabled. Visually it all works as expected, but I'd like to cover this in my unit testing as well.
The below is shortened example as how I tried checking whether the button element is disabled or not. However it seems the page.submitBtnEl.disabled attribute is always true for some reason.
let InvalidUser = new User({
username: '',
password: ''
});
it('form validity should be False when entering invalid credentials',
fakeAsync(() => {
updateForm( InvalidUser );
expect( page.submitBtnEl.disabled ).toBeTruthy("submit button is disabled");
expect(comp.loginForm.valid).toBeFalsy();
}));
Add fixture.detectChanges() call before querying for your element and making the assertions.
it('should be disabled when comment is empty', () => {
updateForm( InvalidUser );
fixture.detectChanges() // <-- add this to update the view
submitBtn = fixture.debugElement.query(By.css('button.btn-default'));
// this asserts that button matches <button disabled>Hello</button>
expect(submitBtn.nativeElement.getAttribute('disabled')).toEqual('');
// this asserts that button matches <button>Hello</button>
expect(submitBtn.nativeElement.getAttribute('disabled')).toEqual(null);
});

Happy Coding!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With