Angular RouterTestingModule 测试未在路由器出口中呈现组件

Angular RouterTestingModule test not rendering components in router-outlet

您好,我正在尝试编写一个集成测试来测试是否为给定路由呈现了正确的组件。

我正在使用英雄之旅应用程序进行此测试。这是完整应用程序的 link(没有下面列出的我的规范文件)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');
    }));
  });

浅层路由有效,因为 URL "/dashboard" 被正确路由到。虽然 console.log 的输出是

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-->

导航到此 URL 时,我希望看到 dom 的其余部分呈现在 <router-outlet _ngcontent-a-c16=""></router-outlet>

或以下

如何对 AppComponent 的子组件进行集成测试,以便我可以进一步进行这些测试,并在子组件上执行类似点击操作等操作,并验证为给定的组件呈现了正确的组件 URL?

解决方案

我将所有子组件添加到 TestBed.configureTestingModule 中的导入数组,并使用 MockHeroService 模拟提供程序 HeroService。我添加了第二个测试以确保导航到 /heroes 实际显示我期望的英雄组件。

我还为英雄中的每个 li 添加了一个 data-test-id,这样我就可以确保数据是从 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');
    }));
  });

您必须将要从路由定义中呈现的每个组件(DashboardComponent、HeroDetailComponent、HeroesComponent)添加到 TestBed 的 declarations 数组中。

示例:

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

有时您会使用组件库,这些库将添加到 imports 数组中。

示例:

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