Search code examples
angularkarma-jasminebdd

When behaviour-testing Angular Components is it possible to lookup the instance of another Component?


I am testing an Angular toolbar component which triggers state-changing actions via @ngrx/store.

I have another component that is subscribed to those state changes in order to update its own internal state.

So in a karma/jasmine unit test, I trigger the click of a toolbar button. I simply then want to spy on the other component and assert it's change function was called.

So the question is, without changing the the existing components with ViewParent/ViewChild directives just for the tests which ofc would be considered a code-smell, how do I lookup the instance of an Angular Component?


Solution

  • It is possible to get the correct instance of a child component in order test behaviours like this.

    You can query the parent to find a child by directive:

    import { By } from '@angular/platform-browser';
    ...
    let childComponentInstance: ChildComponent;
    
    // After setting up your component in the TestBed...
    parentComponentFixture = TestBed.createComponent(ParentComponent);
    ...
    
    // Reference the child component from your parent component fixture
    childComponentInstance = parentComponentFixture
        .debugElement
        .query(By.directive(ChildComponent))
        .componentInstance;
    

    You can then use childComponentInstance in your test methods.

    As you mentioned, this is no longer really a unit test and more of a behaviour test.

    (It may be necessary to call detectChanges() on the parentComponentFixture to properly load the child depending on what is being bound to it)