我想编写一个简单的测试用例,以测试当我按下“提交”按钮并且“名字”字段为空时,它必须在“名字输入”字段下方显示“此字段是必需的”消息。为此,我使用了表单验证来填充错误消息,并且可以正常工作,但是我无法编写适当的测试用例对其进行测试。
测试案例
it('should show "Required" warning when compulsory field is empty', ()=>{
const fixture = TestBed.createComponent(PatientDemographicsComponent);
const app = fixture.debugElement.componentInstance;
fixture.detectChanges();
let firstNameEl = fixture.debugElement.query(By.css('#firstName'));
let savePatientEl = fixture.debugElement.query(By.css('#icn-setting'));
fixture.detectChanges();
firstNameEl.nativeElement.value= "";
fixture.detectChanges();
savePatientEl.triggerEventHandler("click",null);
fixture.detectChanges();
expect(app.formErrors.firstName).toEqual('This field is required');
});
HTML
...
..
.
<!--Input-->
<div class="form-group row">
<label class="col-lg-4 col-form-label" i18n="@@lblFirstName">First Name <span class="required">*</span> </label>
<div class="col-lg-8">
<div class="input-group">
<input class="form-control" id="firstName" (keypress)="validateName($event)"
[ngClass]="formErrors.firstName ? 'is-invalid' : ''" formControlName="firstName" maxlength="30"
kendoTextBox>
<div class="input-group-append">
<input class="form-control middle" placeholder="Middle" maxlength="25" kendoTextBox>
</div>
<div [ngClass]="formErrors.firstName ? 'invalid-feedback': ''" class="invalid-feedback">
{{ formErrors.firstName }}</div>
</div>
</div>
</div>
...
....
...
<!--Save link-->
<div class="col-lg-6">
<div class="form-group row">
<div class="col-lg-12">
<a style="cursor: pointer;" id="icn-setting" class="float-right" (click)="onClickSavePatient()">
<img src="assets/images/load-btn.png" class="img-responsive" alt="">
</a>
</div>
</div>
...
..
.
我使用formErrors模型保存错误消息
component.ts
public formErrors = {
firstName: '',
lastName: '',
previousName: '',
DOB: '',
gender: '',
SSN: '',
workStatus: '',
maritalStatus: '',
mobilePhoneNumber: '',
HomePhoneNumber: '',
OfficePhoneNumber1: '',
ContactPreference: '',
email: '',
address1: '',
address2: '',
state: '',
zipCode: '',
city: '',
locationId: ''
};
//function on submit
public onClickSavePatient() {
this.setPatientDemographics();
console.log(this.patientDemographicsForm);
if (this.patientDemographicsForm.valid) {
this.patientDemographics.name.middleName = this.patientDemographics.name.title = 'Mr';
if (this.patientDemographics.id === undefined || this.patientDemographics.id < 0) {
this.store.dispatch(new PatientAction.AddPatient(this.patientDemographics));
} else {
this.store.dispatch(new PatientAction.UpdatePatient(this.patientDemographics));
}
} else {
this.showFixIssues();
this.checkUntouchedFields = true;
this.formErrors = this.formService.validateForm(this.patientDemographicsForm, this.formErrors, this.checkUntouchedFields);
}
}
现在,运行时因果报应将其显示为空字符串
预计”等于“此字段为必填项”。
希望我已经提供了了解流程所需的一切。 我刚刚开始学习单元测试,因此我必须缺少一个小细节。