如何解决对ngx形式的自定义模板进行单元测试
我正在与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();
});
});
提前谢谢!
解决方法
遇到类似问题。我在模拟组件内部应用了托管形式的方法。我使用了自定义组件,但我认为这会有所帮助:
sudo docker service create -d -p 8090:80 --mount type=bind,src=/var/lib/docker/myTestVolume/_data,dst=/usr/share/nginx/html --mode global nginx
接下来,我在正式模块中注册了自定义包装:
@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}]
})
]
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。