首页 > 解决方案 > 在描述调用中获取夹具和组件值 - Angular 单元测试

问题描述

我正在为包含太多表单的 Web 应用程序编写单元测试。因此,为了代码优化,我正在创建一个将返回 function 的通用函数。该函数测试所有提供的表单字段(ReactiveFroms 方法)是否需要。

测试字段是否需要的函数。

通用功能.spec.ts:

export const componentTestFn = (formGroup: any, fields: Fields[], configurationOptions?) => () => {

describe('On required fields', () => {

    beforeEach(() => {

        if (configurationOptions) {
            TestBed.configureTestingModule(configurationOptions)
                .compileComponents();
        }

    });


    fields.forEach(element => {

        describe(element.name, () => {
            it('should be a required field', () => {

                let control = formGroup.get(element.formControlName);
                if (element.nestedControl) {
                    control = control.get(element.nestedControl);
                }
                control.patchValue('');
                expect(control.hasError('required')).toBeTruthy();
                control.patchValue('Test');
                expect(control.hasError('required')).toBeFalsy();
            });
        });

    });

});

}

我正在使用 describe 子句从主规范文件中调用此函数。

main.component.spec.ts:

describe('Given a Physical Property Setup Component', () => {

     let component: PhysicalPropertySetupComponent;
     let fixture: ComponentFixture<PhysicalPropertySetupComponent>;
     let fields: Fields[] = [
           new Fields('','field1','',''),
           new Fields('','field2','',''),
           new Fields('','field3','',''),
           new Fields('','field4','','')
     ];

     beforeEach(() => {
           TestBed.configureTestingModule({
                 ....
           });
           fixture = TestBed.createComponent(PhysicalPropertySetupComponent);
           component = fixture.componentInstance;
     });
     describe('Testing',common.componentTestFn(component.formGroup,fields));
});

但它给了我错误“TypeError:无法读取未定义的属性'formGroup'”。

我认为这是因为我们只能在it子句中使用组件和夹具值。但我没有使用它,因为我componentTestFn会替换它。同样,当我在里面调用这个函数时,it它工作正常。

谁能告诉我如何formGroup在描述中获得该值?任何帮助将不胜感激。

提前致谢!!

标签: angularunit-testingjasminekarma-jasmine

解决方案


不要将其放入 describe 函数,而是创建一个创建 describe 的函数:

export const componentTestFn = (
  formGroup: any, 
  fields: Fields[], 
  configurationOptions?, 
  componentTested?
) => () => {...});

并这样称呼它:

componentTestFn(common.componentTestFn(component.formGroup, fields, undefined, 'Testing'));

推荐阅读