I'm trying to test the child component, but it requires a parent component for its main functionalities.
How can I test the child component with a "mock" parent?
(Using Jest, Angular 14, TypeScript)
parent.component.ts
@Component({...})
export class ParentComponent {
onChildClicked(child: ChildComponent) {
// ...
}
}
child.component.ts
@Component({...})
export class ChildComponent {
constructor(private parent: ParentComponent) {}
onClick() {
this.parent.onChildClicked(this);
}
}
child.component.spec.ts
describe("ChildComponent", () => {
it("should be rendered", async () => {
const { container } = await render(ChildComponent, {
declarations: [ParentComponent],
});
expect(container).toBeTruthy();
});
});
page.component.html
<app-parent>
<app-child></app-child>
</app-parent>
Test output:
ChildComponent › should be rendered
NullInjectorError: R3InjectorError(DynamicTestModule)[ParentComponent -> ParentComponent]:
NullInjectorError: No provider for ParentComponent!