I have a component (Parent), which has a custom nested component (ChildOne) which has its own custom nested component (ChildTwo). I want to unit test Parent, so I have created stubs for the children. However, stubbing a component seems to cause it not to have any children, so ChildTwo is missing which is needed for my test. Is there a way I can stub a component, while keeping it’s children?
HTML:
<app-child-one>
<p></p>
<div>
<app-child-two (click)="onClick($event)">
</app-child-two>
</div>
</app-child-one>
Typescript:
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss']
})
export class ParentComponent {
onClick(event: Event) {
console.log(event);
}
}
Spec:
@Component({ selector: 'app-child-one', template: '' })
export class ChildOneStubComponent {
}
@Component({ selector: 'app-child-two', template: '' })
export class ChildTwoStubComponent {
}
describe('ParentComponent', () => {
let component: ParentComponent;
let fixture: ComponentFixture<ParentComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [
ParentComponent, ChildOneStubComponent, ChildTwoStubComponent
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ParentComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeDefined();
});
it('calls onClick when child two is clicked', () => {
const childTwo = fixture.debugElement.query(By.css('app-child-two'));
childTwo.triggerEventHandler('click', null); // <-- this fails, child two is null
expect(...);
});