I am writing unit test with karma in Angular and i am struggling with weird problem. I am trying to test output cancel of app-source-roll-history-form
which is inside source-roll-history.dialog.ts
. To achive this i need instance of child component. When I am trying to get it, parent component instance is returned insted of child component instance.
source-roll-history-dialog.html
<ng-template #newRollContent>
<app-source-roll-history-form
(save)="assignNewRoll$.next($event)"
(cancel)="newAssignmentForm = false">
</app-source-roll-history-form>
</ng-template>
source-roll-history-dialog.spec.ts
it('should show/hide form to assign new roll', () => {
...
const instance = fixture.debugElement.query(By.css('app-source-roll-history-form')).componentInstance;
console.log(fixture.debugElement.query(By.css('app-source-roll-history-form')));
console.log(instance);
});
console.log(fixture.debugElement.query(By.css('app-source-roll-history-form'))); gave me debug element like this:
<app-source-roll-history-form _ngcontent-a-c295=""></app-source-roll-history-form>
so that is fine. But when I am trying to get instance of this component:
fixture.debugElement.query(By.css('app-source-roll-history-form')).componentInstance
I am getting instance of parent:
SourceRollsHistoryDialogComponent{actions$: Actions{_subscribe: observer => { ... }}, toasterService: ToasterService{toastrService: ToastrService{overlay: ...,
Disclaimer: This answer does not explain how to get the component instance of the child, but it offers other approaches to solve the problem behind.
In the question, the component instance of the child component is needed to trigger an output event on the child. This can be done in different ways:
Or if you do not want to interact with the child component (eg because the setup for it is too complicated):
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.