Angular2 2.0.0 组件单元测试导致错误 : Bootstrap at least one component before injecting Router

标签 angular jasmine router angular-cli angular2-testing

看了之前的类似问题,似乎一直没有明确的答案。

这是正在发生的事情。我正在使用 angular-cli 工具构建一个 angular2 应用程序(运行 beta 16,angular 2.0.1 和路由器 3.0.1。

当我运行“ng test”时,我的所有测试都通过了,期待我的 app.component。 (ng serve 工作正常等)

这是一些代码:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { HealthComponent } from './health/health.component';
import { MonitorModule } from './monitor/monitor.module';
import { PlanComponent } from './plan/plan.component';
import { ConfigureComponent } from './configure/configure.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { TroubleshootComponent } from './troubleshoot/troubleshoot.component';
import { HeaderComponent } from './ui/header/header.component';
import { OnboardingModule } from './onboarding/onboarding.module';
import { routing, appRoutingProviders }  from './app.routing';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing,
    MonitorModule,
    OnboardingModule
  ],
  declarations: [
    AppComponent,
    HomeComponent,
    HealthComponent,
    PlanComponent,
    ConfigureComponent,
    DashboardComponent,
    TroubleshootComponent,
    HeaderComponent
  ],
  providers: [
    appRoutingProviders
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent  {

}

app.component.spec.ts

/* tslint:disable:no-unused-variable */

import { TestBed, async } from '@angular/core/testing';
import { APP_BASE_HREF } from '@angular/common';
import { routing, appRoutingProviders }  from './app.routing';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { HeaderComponent } from './ui/header/header.component';
import { HealthComponent } from './health/health.component';
import { PlanComponent } from './plan/plan.component';
import { ConfigureComponent } from './configure/configure.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { TroubleshootComponent } from './troubleshoot/troubleshoot.component';

describe('App: Ng2Test2', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        HeaderComponent,
        HomeComponent,
        HealthComponent,
        PlanComponent,
        ConfigureComponent,
        DashboardComponent,
        TroubleshootComponent
      ],
      imports: [
        routing
      ],
      providers: [
        appRoutingProviders,
        { provide: APP_BASE_HREF, useValue : '/' }
      ]
    });
  });

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

app.component.html

  <app-header></app-header>

  <router-outlet></router-outlet>

最后,这是我在运行“ng test”时遇到的错误:

App: Ng2Test2 should create the app FAILED
    Failed: Error in ./AppComponent class AppComponent - inline template:2:2 caused by: Bootstrap at least one component before injecting Router.
    Error: Bootstrap at least one component before injecting Router.
        at setupRouter (webpack:///Users/jtaylor/Projects/hmng-angular/hmng-ng2/~/@angular/router/src/router_module.js:190:0 <- src/test.ts:29132:15)

我已经尝试了很多不同的方法来防止这个错误,但无法让这个错误停止!

对此有什么想法吗?

编辑:我追踪到这个组件,我在我的构造函数中使用路由器:

header.component.ts

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { AppComponent } from '../../app.component';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html'
})
export class HeaderComponent implements OnInit {

  section: any;
  // router: Router;
  // activateRoute: ActivatedRoute;

  constructor(
    public router: Router,
    public activatedRoute: ActivatedRoute
  ) {}

  ngOnInit() {
    this.router.events.subscribe(e => {
      if (e instanceof NavigationEnd) {
        this.setActiveNavTab(e.url.replace(/^\/([^\/]*).*$/, '$1'));
      }
    });
  }

  setActiveNavTab(section: string) {
    this.section = section;
  }

}

那么,我如何通过单元测试在该构造函数之前引导组件?

最佳答案

这是因为您正在尝试使用 RouterModule 进行测试。相反,您应该使用 RouterTestingModule 并使用 RouterTestingModule.withRoutes

添加您的路由
import { RouterTestingModule } from '@angular/router/testing';

imports: [
  // routing
  RouterTestingModule.withRoutes(APP_ROUTES)
]

关于Angular2 2.0.0 组件单元测试导致错误 : Bootstrap at least one component before injecting Router,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39902606/

相关文章:

javascript - 主干路由器监听器未命中哈希标签

javascript - 根据 Typescript 中的值对所有 JSON 键进行分组

Angular2 将动画绑定(bind)到伪元素

Angular 16 takeUntilDestroyed 运算符具有两种订阅方法

node.js - PhantomJS 意外退出,退出代码为 -1073741819

angular - Angular2 中 api 调用后重定向到路由

javascript - Angular 8 + RxJS 以及合并 flatMap 和 forkJoin 的问题

javascript - 如何在 AngularJS 中使用 $http.jsonp 对函数进行单元测试?

angular - 从 Angular 11.0.3 开始,e2e 测试会产生错误

刷新另一个页面时, Angular 路由重定向到主页