测试使用服务茉莉花间谍对象的函数



我正在尝试测试按按钮启动的函数

如果按钮值等于"是",将自定义验证器应用于FormGroup

验证器需要一个参数,该参数为" this.stateservice",该测试返回一个数字" 0"。

实际功能:

  onSelected(): void {
        const myFormGroup: AbstractControl = this.form.controls.fGroup;
            if (this.form.get('button').value === 'Yes') {
                myFormGroup.validator = myValidation.requireCheckboxesToBeChecked(this.stateService);
                } else {
                myFormGroup.setValidators(null);
                }
            myFormGroup.updateValueAndValidity();
    }

在验证器文件中:

static requireCheckboxesToBeChecked(stateService: StateService): ValidatorFn {
    return function validate (formGroup: FormGroup): { [key: string]: boolean } | null  {
      const checkedCount = stateService.currentCheckedCount();
      if (checkedCount === 0) {
          return  {
            'isNotChecked' : true
          };
        }
      return null;
    };
  }

测试功能:

import { myValidation } from '@app/shared/validators/modification.validator';
const mockStateService = jasmine.createSpyObj('StateService',
    [ 'getCategoryState',
      'getCheckedCount'
    ]);
  it('should add validation to my form group when value is Yes', () => {
    const vehicleModificationsFormGroup = component.form.controls['vehicleModifications'];
    component.form.get('button').setValue('Yes');
    component.onSelected();
    myFormGroup.validator = myValidation.requireCheckboxesToBeChecked(mockStateService);
    expect(mockStateService.currentCheckedCount).toEqual(0);
    expect(myFormGroup.validator.length).toBe(1);
  });

我正在获得" stateservice.currentcheckedcount不是函数",它在验证器文件中

您定义的模拟(mockStateService)没有currentCheckedCount方法。

mockStateService只有两种方法getCategoryStategetCheckedCount

如果您只想模拟对象的某些方法,则可以在示例服务的实例上尝试spyOn

  • 链接到间谍嘲笑呼叫
  • 链接到Spyon嘲笑一种方法并能够使用参数
  • 链接到间谍的链接嘲笑一种方法并调用真实的方法

等等,还有其他选择可以监视/模拟某些方法。

您还可以尝试使用CreateSpyObj:

来定义要返回的内容
const mockStateService = jasmine.createSpyObj('StateService',  
    { 
       getCategoryState: function() {
          return "ifItMathersReturnSomething";
       },
       getCheckedCount: function() {
          return "anotherThing";
       },
       currentCheckedCount: function() {
          return 0;
       } 
   }
);

但是,我确实必须修改对MockService的调用以返回值,而不是等于

    import { myValidation } from '@app/shared/validators/modification.validator';
    const mockStateService = jasmine.createSpyObj('StateService',
             [ 'currentCheckedCount',
               'getCheckedCount'
             ]);
    it('should add validation to my form group when value is Yes', () => {
    const vehicleModificationsFormGroup = component.form.controls['vehicleModifications'];
    component.form.get('button').setValue('Yes');
    component.onSelected();
    myFormGroup.validator = myValidation.requireCheckboxesToBeChecked(mockStateService);
    mockStateService.currentCheckedCount.and.returnValue(0);
    expect(myFormGroup.validator.length).toBe(1);
  });

最新更新