I am running an Angular 5 application with the default test setup (Jasmine + Karma).
Let's say there is a component named Parent, having a method executing a method on child component.
parent.component.ts
@Component({
selector: 'parent',
...
export class ParentComponent implements {
@ViewChild(ChildComponent) childComponent: ChildComponent;
executeChildComponentMethod() {
this.childComponent.methodToTest();
}
}
parent.component.spec.ts
import { ParentComponent } from './parent.component'
describe('ParentComponent' () => {
let component: ParentComponent;
let fixture: ComponentFixture<ParentComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ParentComponent],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ParentComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should trigger executeChildComponentMethod', () => {
component.executeChildComponentMethod()
});
});
This results in the tests throwing error saying, unable to execute methodToTest of undefined.. which means the child component is not instantiated.
Have tried approaches like instantiating a child component inside the it block, injecting the child component to the it block and instantiating child component from another fixture (for child component) in the test block but to no avail.
How can I get the test working?
ng serve? If so you will have to add your child component template in your question mentioning that error. Well, that is probably another question. If you google it you will get many posts. I would suggest you to close this question and ask new one, since this question is related to child component invocation only. Else it would be confusing for future readers.