gpt4 book ai didi

angular - 如何测试包含自定义表单控件的组件?

转载 作者:太空狗 更新时间:2023-10-29 18:29:14 47 4
gpt4 key购买 nike

我有这样一个组件

@Component({
selector: 'app-custom-form-control',
templateUrl: '<input>',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => SelectComponent),
multi: true
}
]
})
export class CustomFormControlComponent implements ControlValueAccessor {...}

如您所见,它是一个自定义表单控件。我在要测试的组件中使用它。

    @Component({
selector: 'app-root',
templateUrl: '<div [formGroup]="form">
<app-custom-form-control formControlName="my_field"></app-custom-form-control>
</div>',
})
export class AppComponent implements OnInit, OnDestroy {...}

那么我如何为我的测试模拟 app-custom-form-control

当前的实现需要一个真正的组件...

  beforeEach(async(() => {
const testRouter = new RouterStub();
const testDataService = new DataServiceStub();
TestBed.configureTestingModule({
declarations: [
AppComponent,
CustomFormControlComponent // it is a real stuff
],
imports: [
ReactiveFormsModule
],
providers: [
{ provide: Router, useValue: testRouter },
{ provide: DataService, useValue: testDataService }
],
schemas: [ NO_ERRORS_SCHEMA ]
}).compileComponents();
}));

否则(没有声明组件)我得到一个错误失败:没有名称的表单控件的值访问器:app-custom-form-control

最佳答案

在对 Angular 应用程序进行测试时,您可以遵循两种主要方法(和混合):

1- Stubbing unneeded components , 其中

(...) you create and declare stub versions of the components anddirective that play little or no role in the tests (...)

2-NO_ERRORS_SCHEMA哪个

(...) tells the Angular compiler to ignore unrecognized elements and attributes (...)

对于最后一个,编译器在 AppComponent 模板中遇到 app-custom-form-control 选择器时不会抛出错误。

3- Use both techniques together

选择一种或另一种方法完全取决于您,因为这取决于您要通过测试达到的最终目标。


应用方法 1 会是这样的:

describe('AppComponent', () => {

// component stub
@Component({selector: 'app-custom-form-control', template: ''})
class CustomFormControlComponentStub {}
//...
beforeEach(async(() => {
const testRouter = new RouterStub();
const testDataService = new DataServiceStub();
TestBed.configureTestingModule({
declarations: [
AppComponent,
CustomFormControlComponentStub // it is fake! stuff
],
// ... code omitted
}).compileComponents();
}));
//...
});

关于angular - 如何测试包含自定义表单控件的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50821486/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com