根据标题,如何在 Angular 单元测试中提供 ControlContainer
?
以下是产生的错误:
NullInjectorError: StaticInjectorError(DynamicTestModule)[ChildFormComponent -> ControlContainer]:
StaticInjectorError(Platform: core)[ChildFormComponent -> ControlContainer]:
NullInjectorError: No provider for ControlContainer!
我尝试提供ControlContainer
:
beforeEach(() => {
const parentFixture = TestBed.createComponent(ParentFormComponent);
const parentComponent = parentFixture.componentInstance;
parentComponent.initForm();
fixture = TestBed.createComponent(ChildFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
我见过其他使用以下方法的解决方案:
declarations: [
...MY_DECLARATIONS
],
imports: [
...MY_IMPORTS
],
providers: [
{
provide: ControlContainer,
useValue: MyFormGroupDirective
}
]
我运气不好,但如果这里有人能够提供一些线索;我将不胜感激。
最佳答案
我能够从这篇文章中得出解决方案:
How to mock ControlContainer in angular unit test?
我最终做的是:
let component: MyChildComponent;
let fixture: ComponentFixture<MyChildComponent>
let fg: FormGroup;
let fgd: FormGroupDirective;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [ ...MY_DECLARATIONS ],
imports: [ ...MY_IMPORTS ],
providers: [
{ provide: ControlContainer, useValue: fgd }
]
});
});
beforeEach(() => {
const parentFixture = TestBed.createComponent(MyParentComponent);
const parentComponent = parentFixture.componentInstance;
fg = parentComponent.form;
fgd = new FormGroupDirective([], []);
fgd.form = fg;
const childFixture = TestBed.createComponent(MyChildComponent);
const childComponent = childFixture.componentInstance;
childFixture.detectChanges();
});
我想做的是将初始化的父表单组附加到子表单组。
关于angular - 如何在 Angular 组件的单元测试中提供 ControlContainer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60940130/