angular - 如何测试包含自定义表单控件的组件?
问题描述
我有一个这样的组件
@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();
}));
否则(没有声明组件)我得到一个错误Failed: No value accessor for form control with name: app-custom-form-control
解决方案
在对 Angular 应用程序进行测试时,您可以遵循两种主要方法(和混合方法):
1-存根不需要的组件,其中
(...)您创建和声明在测试中几乎没有作用的组件和指令的存根版本(...)
2-NO_ERRORS_SCHEMA
哪个
(...) 告诉 Angular 编译器忽略无法识别的元素和属性 (...)
使用最后一个,编译器在遇到模板中的app-custom-form-control
选择器时不会抛出错误。AppComponent
选择一种或另一种方法,这取决于您,因为这取决于您在测试中的最终目标。
应用方法 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();
}));
//...
});
推荐阅读
- python - 什么是梯度下降。梯度下降能比sklearn线性回归算法给出更好的结果吗
- list - `seqn` 和 `sequenceA` 之间的关系和区别是什么?
- python - Python onedrivesdk - invalid_request 错误
- javascript - 如何检测对象值何时发生变化?
- javascript - 将数字数组与“数字数组数组”进行比较以查找匹配项
- canvas - 有什么方法可以在 Leaflet 地图上徒手绘制?
- c# - 单个 MongoDB 实例上的 C# MongoDB 驱动程序事务
- javascript - 记录执行 aync await 函数所用的时间
- css - 使外部库(语义 ui React)和 CSS 模块与 webpack css-loader 一起工作
- azure-devops - 即使在 azure devops 中删除后如何保留文件夹