我有一个简单的表格,有2个输入框和一个提交按钮。
<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>
现在当2个输入框为空时,应禁用提交按钮。 在视觉上它一切都按预期工作,但我也想在我的单元测试中讨论这个问题。
下面是缩短示例,我尝试检查按钮元素是否被禁用。但是,由于某种原因,似乎page.submitBtnEl.disabled
属性始终为真。
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();
}));
答案 0 :(得分:0)
在查询元素并进行断言之前添加 fixture.detectChanges()
调用。
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);
});
快乐编码!