简体   繁体   中英

How to properly get child component instance in Angular unit test?

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:

  1. Use the user interface to trigger the cancel event, ie do whatever the user would have to do to trigger this event. (Probably this means clicking on a cancel button somewhere? This would be my preferred solution.)

Or if you do not want to interact with the child component (eg because the setup for it is too complicated):

  1. Use a mocking library like ngMocks to mock the child component and to emit an event from the mocked child . This also saves you from having to declare or provide dependencies of the child component in the TestBed.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM