[英]How do I provide ControlContainer inside an Angular component's unit test?
As per the title, how can I provide ControlContainer
inside an Angular unit test?根据标题,如何在 Angular 单元测试中提供
ControlContainer
?
The following is the error produced:以下是产生的错误:
NullInjectorError: StaticInjectorError(DynamicTestModule)[ChildFormComponent -> ControlContainer]:
StaticInjectorError(Platform: core)[ChildFormComponent -> ControlContainer]:
NullInjectorError: No provider for ControlContainer!
My attempt to provide ControlContainer
:我尝试提供
ControlContainer
:
beforeEach(() => {
const parentFixture = TestBed.createComponent(ParentFormComponent);
const parentComponent = parentFixture.componentInstance;
parentComponent.initForm();
fixture = TestBed.createComponent(ChildFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
I have seen other solutions that use:我见过其他使用以下解决方案的解决方案:
declarations: [
...MY_DECLARATIONS
],
imports: [
...MY_IMPORTS
],
providers: [
{
provide: ControlContainer,
useValue: MyFormGroupDirective
}
]
I have had no luck but if there is anyone here who is able to shed some light;我没有运气,但如果这里有人能够阐明; I would deeply appreciate it.
我会深深地感激它。
I was able to derive the solution from this post:我能够从这篇文章中得出解决方案:
How to mock ControlContainer in angular unit test? 如何在角度单元测试中模拟 ControlContainer?
What I ended up doing was:我最终做的是:
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();
});
What I wanted to do was attach the initialized parent form group to the child.我想做的是将初始化的父表单组附加到子表单组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.