我正在尝试在Angular 8中测试子组件
子组件取决于其父组件功能,并且父组件不应该知道子组件,它可以是几种不同类型的子组件之一
在子组件中,我通过将其注入到构造函数中来获得对父组件的引用:
export class ChildComponent {
constructor(
@Inject(forwardRef(() => ParentComponent)) public parent: ParentComponent
) { }
}
问题是,当我尝试为子组件编写单元测试时,Karma会引发错误:No provider for ParentComponent
我在提供程序中添加了ParentComponent
组件,该错误消失了,但是它仍然不起作用,例如致电childComponent.parent.ngOnInit()
会得到TypeError: Cannot read property 'ngOnInit' of undefined
如何让父组件在子组件测试中工作?
import { ComponentFixture, TestBed } from '@angular/core/testing';
describe('Create Child Component', () => {
let component: ChildComponent;
let fixture: ComponentFixture<ChildComponent>;
let componentElement: HTMLElement;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
ParentComponent,
ChildComponent,
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ChildComponent);
component = fixture.componentInstance;
componentElement = fixture.debugElement.nativeElement;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
expect(component.parent).toBeTruthy();
component.parent.ngOnInit();
});
});