Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

testing if button is disabled

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();
  })); 
like image 675
Alexus Avatar asked Jun 01 '26 11:06

Alexus


1 Answers

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);
});

enter image description here

Happy Coding!

like image 144
Bhavin Avatar answered Jun 03 '26 01:06

Bhavin



Donate For Us

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