Angular 2 - 带路由器插座的测试组件

Mos*_*sar 19 javascript testing karma-runner angular2-routing angular

我用angular-cli创建了角度2项目.我创建了单独的AppRoutingModule,它导出了RouterModule并被添加到AppModule进口数组中.

我还有由angular-cli创建的appComponent.

app.component.html

<nav>
  <a *ngFor="let view of views" routerLink="{{ view.address }}" routerLinkActive="active">{{ view.text }}</a>
</nav>
<router-outlet></router-outlet>
Run Code Online (Sandbox Code Playgroud)

app.component.spec.ts

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';


describe('App: AquaparkFrontend', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
    });
  });

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

  it(`should have 3 views`, () => {
    let fixture = TestBed.createComponent(AppComponent);
    let app = fixture.debugElement.componentInstance;
    expect(app.views.length).toEqual(3);
  });
});
Run Code Online (Sandbox Code Playgroud)

当我尝试使用ng测试运行测试时,我有错误:

 Can't bind to 'routerLink' since it isn't a known property of 'a'. ("<nav>
      <a *ngFor="let view of views" [ERROR ->]routerLink="{{ view.address }}" routerLinkActive="active">{{ view.text }}</a>
    </nav>
    <router-outlet><"
Run Code Online (Sandbox Code Playgroud)

我是否会错过在测试中导入的内容?

Ali*_*eza 30

<router-outlet> 是Angular2 +中的一个组件,因此需要被识别.

所以你需要RouterTestingModule测试路由,否则,你得到错误,从你的规范中的路由器/测试中导入它:

import { RouterTestingModule } from '@angular/router/testing';
Run Code Online (Sandbox Code Playgroud)


然后在这样的import[]部分中使用它:

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports:[
        RouterTestingModule //<<< import it here also
      ],
      declarations: [
        AppComponent
      ],
      providers: [{ provide: APP_BASE_HREF, useValue: '/' }]

    }).compileComponents();
  }));
Run Code Online (Sandbox Code Playgroud)


Pau*_*tha 21

仅供参考,TestBed用于从头开始为测试环境创建模块.所以这AppModule并没有给你任何帮助.

在您的情况下,如果您根本不想测试任何路由,则可以使用NO_ERRORS_SCHEMA而不是使用而忽略此错误CUSTOM_ELEMENTS_SCHEMA.后者将避免与HTML元素相关的错误,但前者将忽略所有错误,包括未知的绑定属性.

如果您确实想对某些路由内容进行一些测试,那么您需要配置一些路由.你可以用RouterTestingModule,这是替代RouterModule.您可以在以下链接中找到一些好的示例,而不是发布一些任意示例