【问题标题】:Unit test angular case switch formControl单元测试角案例开关formControl
【发布时间】:2021-06-07 07:59:40
【问题描述】:

我正在尝试使用单元测试来测试一些功能,比如这样

  public setFormControlsValue(formControl: AbstractControl, buildingType: buildingTypeOption, value?: string): void {
    switch (buildingType) {
      case buildingTypeOption.twoToFourFacades:
      case buildingTypeOption.additionalConstruction:
      case buildingTypeOption.industrialBuilding:
        formControl.setValidators([Validators.required]);
        formControl.updateValueAndValidity();
        formControl.enable({ onlySelf: true });
        break;
      case buildingTypeOption.lightConstruction:
        debugger
        formControl.setValidators(null);
        formControl.setValue(null);
        formControl.clearValidators();
        formControl.updateValueAndValidity();
        formControl.disable({ onlySelf: true });
        break;
      case null:
        formControl.setValidators([Validators.required]);
        formControl.setValue(null);
        formControl.updateValueAndValidity();
        formControl.enable({ onlySelf: true });
        break;
      default:
        formControl.setValue(value);
        formControl.updateValueAndValidity();
        formControl.disable({ onlySelf: true });
        break;
    }
  }

在单元测试中是这样的

describe('has called setFormControlsValue ', () => {
    let formControlsValue = {};
    let formBuilder = new FormBuilder();
    let formControls: AbstractControl;

    beforeEach(() => {
      formControlsValue = {
        destinationEquipment: destinationEquipment.nonEquippedDestination
      };
      formControls = formBuilder.group(formControlsValue);
    });
    it('formControls should be twoToFourFacades and enabled', () => {
      // GIVEN
      // WHEN
      service.setFormControlsValue(formControls, buildingTypeOption.twoToFourFacades);
      // THEN
      expect(formControls.disabled).toBeFalsy();
    });
  });

我遇到的问题是如何测试这行代码 formControl.setValidators([Validators.required]); 或者我的设置测试方向不正确?

【问题讨论】:

    标签: angular unit-testing


    【解决方案1】:

    如何测试这行代码 formControl.setValidators([Validators.required]);

    在准备好的条件下,执行相关代码,然后检查formControl是否无效,是否有正确的{required:true}错误。

    expectThat(formControl.invalid).toBeTrue();
    expectThat(formControl.errors).toEqual({required:true});
    

    【讨论】:

      猜你喜欢
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-01
      • 2020-01-15
      • 1970-01-01
      相关资源
      最近更新 更多