如何使用angular和bootstrap在表单输入中测试客户端验证?

时间:2018-08-01 09:43:03

标签: angular unit-testing validation input jasmine

我正在尝试在此标记上测试必需的属性

<div id="div_formDeviceName" class="form-group was-validated"        [ngClass]="{'has-error': !isNameUnique || !(myName.valid || myName.pristine)}">
      <label id="lbl_deviceName" >Name *</label>
      <input id="in_deviceName" name="in_alias" #myName="ngModel" maxlength="255" [(ngModel)]="device.name" (blur)="trimName($event)" required>
      <div class="invalid-feedback text-danger" id="div_deviceRequired"
           *ngIf="(myName.errors && myName.errors.required)" translate>Required
      </div>
</div>

因此,如果用户删除输入字段中的名称,则会显示错误消息。

这很好,我想测试一下。

it("client error validation", async(() => {
    component.device = new Device();
    component.device.name = "My unit test device";
    fixture.detectChanges();

    const deviceName: DebugElement = 
      fixture.debugElement.query(By.css("#in_deviceName"));
    const input: HTMLInputElement = deviceName.nativeElement;

    console.debug(input.value);
    expect(input.attributes
      .getNamedItem("ng-reflect model").value)
        .toBe(component.device.name);
    input.value = "";
    input.dispatchEvent(new Event("input"));
    fixture.whenStable().then(() => {    
      fixture.detectChanges();
      const divError: DebugElement = 
        fixture.debugElement.query(By.css("#div_deviceRequired"));
      const divErrRequired: HTMLInputElement = divError.nativeElement;

      expect(divErrRequired).toBeDefined();
    });

但是测试中的输入值永远不会改变并且div查询失败...

0 个答案:

没有答案