【问题标题】:Unit Testing an ngx-formly Custom Template对 ngx-formly 自定义模板进行单元测试
【发布时间】:2021-01-30 11:40:55
【问题描述】:

我正在使用Formly 并创建了几个自定义模板。组件中包含的唯一代码是对一般错误处理服务的调用,因此除了可以创建组件之外几乎没有什么要测试的。我只使用 Jest 进行单元测试,但无法弄清楚我需要包含什么才能使组件成功编译。

我得到的错误是:TypeError:无法读取未定义的属性“formControl”。我不确定我在测试中遗漏了什么。

对于最简单的组件(主要是样式和指令 - 现在已删除),我有以下内容:

组件:

@Component({
  selector: 'my-formly-field-input',
  templateUrl: './formly-field-input.component.html',
  styleUrls: ['./formly-field-input.component.scss']
})
export class FormlyFieldInputComponent extends FieldType {

  constructor(private formErrorService: FormErrorHandlerService) {
    super();
  }

  getError(formItem: FormControl | FormGroup | FormArray): string {
    return this.formErrorService.getFormError(formItem);
  }

}

查看:

<mat-form-field [floatLabel]="'always'" 
                class="w-100" 
                [appearance]="'fill'">
    <mat-label>{{field.templateOptions.label}}</mat-label>
    <input matInput 
           [formControl]="formControl"
           [type]="field.templateOptions.type || 'text'"
           [step]="field.templateOptions.step || 1"
           [max]="field.templateOptions.max || undefined"/>
    <mat-error *ngIf="formControl.errors">
        {{getError(formControl)}}
    </mat-error>
</mat-form-field>

单元测试:

 describe('FormlyFieldInputComponent', () => {
  let component: FormlyFieldInputComponent;
  let fixture: ComponentFixture<FormlyFieldInputComponent>;

  const formHelperServiceStub: Partial<FormErrorHandlerService> = {
    getFormError: (formItem) => 'Error Happened'
  };

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        FormlyFieldInputComponent
      ],
      imports: [
        MyHelpersModule,
        BrowserAnimationsModule,
        FormlyModule.forRoot(),
        FormlyMaterialModule,
        MatFormFieldModule,
        MatInputModule,
        ReactiveFormsModule,
      ],
      providers: [
        { provide: FormErrorHandlerService, useValue: formHelperServiceStub }
      ],
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(FormlyFieldInputComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

提前致谢!!

【问题讨论】:

    标签: angular angular-material jestjs ngx-formly


    【解决方案1】:

    面临类似的问题。我在模拟组件内应用了托管表单的方法。我使用了一个自定义组件,但我认为它会有所帮助:

    @Component({
      selector: 'app-test-cmp',
      template: `
        <form [formGroup]="form">
          <formly-form [model]="{}" [fields]="fields" [options]="{}" [form]="form"></formly-form>
        </form>`
    })
    class MockFormComponent  {
      form = new FormGroup({ });
      fields: FormlyFieldConfig[] = [{
        wrappers: ['your custom wrapper name'],
        defaultValue: {}
      }];
    }
    

    接下来,我在正式模块中注册了自定义包装器:

    TestBed.configureTestingModule({
          imports: [
            ... Your dependencies will be here,
            FormlyModule.forRoot({
              wrappers: [{'your custom wrapper name', component: FormlyFieldInputComponent}]
            })
           ] 
    })
    

    并初始化组件:

    beforeEach(() => {
        fixture = TestBed.createComponent(MockFormComponent);
        mockComponent = fixture.componentInstance;
        fixture.detectChanges();
        component = fixture.debugElement.query(By.directive(FormlyFieldInputComponent)).componentInstance;
    });
    

    【讨论】:

    猜你喜欢
    • 2021-10-04
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 1970-01-01
    • 2020-12-07
    • 1970-01-01
    相关资源
    最近更新 更多