Search code examples
angularrouter-outletangular-test

Angular RouterTestingModule test not rendering components in router-outlet


Hi I'm trying to write an integration test to test that the correct components are rendered for a given route.

I'm using the tour of heroes app for this test. This is a link to the full app (without my spec file which is listed below) https://angular.io/generated/live-examples/testing/stackblitz.html

app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { DashboardComponent } from './dashboard/dashboard.component';
import { HeroesComponent } from './heroes/heroes.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';

export const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'dashboard', component: DashboardComponent },
  { path: 'detail/:id', component: HeroDetailComponent },
  { path: 'heroes', component: HeroesComponent }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Tour of Heroes';
}

app.component.spec.ts

import { ComponentFixture, TestBed, waitForAsync, fakeAsync, tick } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';

import { AppComponent } from './app.component';
import { routes } from './app-routing.module';
import { Router } from '@angular/router';

describe('AppComponent Routing', () => {
    let component: AppComponent;
    let fixture: ComponentFixture<AppComponent>;
    let router: Router;
  
    beforeEach(waitForAsync(() => {
      TestBed.configureTestingModule({declarations: [AppComponent], imports: [RouterTestingModule.withRoutes(routes)]}).compileComponents();
    }));
  
    beforeEach(() => {
      fixture = TestBed.createComponent(AppComponent);
      router = TestBed.get(Router);
      component = fixture.componentInstance;
      router.initialNavigation();
      fixture.detectChanges();
    });
  
    it('should create', fakeAsync(() => {
      router.navigate(['']);
      tick();
      expect(component).toBeDefined();
      console.log(fixture.debugElement.nativeElement.innerHTML);
      expect(router.url).toBe('/dashboard');
    }));
  });

The shallow routing works, in that the URL "/dashboard" is correctly routed to. Though the output for console.log is

LOG: '<h1 _ngcontent-a-c16="">Tour of Heroes</h1><nav _ngcontent-a-c16=""><a _ngcontent-a-c16="" routerlink="/dashboard" ng-reflect-router-link="/dashboard" href="/dashboard">Dashboard</a><a _ngcontent-a-c16="" routerlink="/heroes" ng-reflect-router-link="/heroes" href="/heroes">Heroes</a></nav><router-outlet _ngcontent-a-c16=""></router-outlet><app-dashboard _nghost-a-c17=""><h3 _ngcontent-a-c17="">Top Heroes</h3><div _ngcontent-a-c17="" class="grid grid-pad"><!--container--></div></app-dashboard><!--container-->

When navigating to this URL I would have expected to see the rest of the dom rendered in or below <router-outlet _ngcontent-a-c16=""></router-outlet>

How do I go about integration testing the child components of AppComponent, so that I can go further with these tests and do like click actions etc on child components and verify the correct components are rendered for a given URL?

Solution

I added all of the child components to the imports array in TestBed.configureTestingModule and mocked out the provider HeroService with a MockHeroService. I've added a second test to ensure that navigating to /heroes actually displays the heroes component that I expect.

I've also added a data-test-id to each li in heroes so I can ensure the data is rendered from the mockService.

import { ComponentFixture, fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { routes } from './app-routing.module';
import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';
import { HeroService } from './hero.service';
import { HeroesComponent } from './heroes/heroes.component';
import { MessageService } from './message.service';
import { MessagesComponent } from './messages/messages.component';
import { Observable, of } from 'rxjs';
import { Hero } from './hero';
import { HEROES } from './mock-heroes';
import { By } from '@angular/platform-browser';

class MockHeroService {
  getHeroes(): Observable<Hero[]> {
    return of(HEROES);
  }

  getHero(id: number): Observable<Hero> {
    return of(HEROES.find(hero => hero.id === id));
  }
}
 
describe('AppComponent Routing', () => {
    let component: AppComponent;
    let fixture: ComponentFixture<AppComponent>;
    let router: Router;
  
    beforeEach(waitForAsync(() => {
      TestBed.configureTestingModule({
        declarations: [AppComponent, DashboardComponent, HeroDetailComponent, HeroesComponent, MessagesComponent],
        imports: [RouterTestingModule.withRoutes(routes), BrowserModule,
          FormsModule],
        providers: [
          { provide: HeroService, useClass: MockHeroService },
          { provide: MessageService }
        ]
      }).compileComponents();
    }));
  
    beforeEach(() => {
      fixture = TestBed.createComponent(AppComponent);
      router = TestBed.inject(Router);
      component = fixture.componentInstance;
      router.initialNavigation();
      fixture.detectChanges();
    });
  
    it('should create', fakeAsync(() => {
      router.navigate(['']);
      tick();
      expect(component).toBeDefined();
      expect(router.url).toBe('/dashboard');
    }));

    it('navigate to heroes', fakeAsync(() => {
      router.navigate(['heroes']);
      tick();
      fixture.detectChanges();
      const heroes = fixture.debugElement.queryAll(By.css('[data-test-id="hero-item"]'));
      console.log(heroes);
      expect(heroes.length).toBe(HEROES.length);
      expect(component).toBeDefined();
      expect(router.url).toBe('/heroes');
    }));
  });

Solution

  • You have to add each component (DashboardComponent, HeroDetailComponent, HeroesComponent) which you want to have rendered from your routing definition to the declarations array of your TestBed.

    Example:

    TestBed.configureTestingModule({
          declarations: [
            AppComponent,
            DashboardComponent,
            HeroDetailComponent,
            HeroesComponent 
          ], 
          imports: [RouterTestingModule.withRoutes(routes)]
        }).compileComponents();
    

    Sometimes you use components libraries, those you would add to the imports array.

    Example:

    await TestBed.configureTestingModule({
      imports: [
        MatTableModule  // will render material table components 
      ],
      declarations: [ AppComponent]
    })
    .compileComponents();