How to unit test if an angular 2 component contains another component

Chan15 picture Chan15 · Nov 11, 2016 · Viewed 21.7k times · Source

I'm quite new to angular 2.

I have a component which in turn has some other components in its template.

How do I write unit tests to check if my parent component consists of other components.

Mentioning a sample or directing me to a resource would be really helpful.

MyComponent.ts:

import { Component } from '@angular/core';
@Component({
selector: 'my-component',
templateUrl: `<div>
<other-component></other-component>
</div>`
})
export class MyComponent{

}

OtherComponent.ts:

import { Component } from '@angular/core';
@Component({
selector: 'other-component',
templateUrl: `<div>
<h1>Other Component</h1>
</div>`
})
export class OtherComponent{

}

Answer

silencedmessage picture silencedmessage · Jun 24, 2017

To test if a component, when compiled, contains other components:

  • Inject the component you're testing
  • Inject the child components
  • Create the parent component
  • Detect changes
  • Use querySelector or querySelectorAll to find the child components

I typically only check that the element exists and then do further testing in the spec for the individual child component.

import { TestBed, async } from '@angular/core/testing';

import { AppComponent } from './app.component';
import { OtherComponent } from './other/other.component';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        OtherComponent
      ],
    }).compileComponents();
  }));

  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));

  it('should have the other component', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('app-other')).not.toBe(null);
  }));
});

Checking for null with querySelector will determine if your component exists. From the querySelector MDN:

Returns null if no matches are found; otherwise, it returns the first matching element.


If you'd like to check that there are multiple instances of the same child component, you can use querySelectorAll and check the length property:

expect(compiled.querySelectorAll('app-other').length).toBeGreaterThan(4);