繁体   English   中英

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

[英]Angular 2 - testing component with router-outlet

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

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);
  });
});

当我尝试使用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><"

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

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

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

import { RouterTestingModule } from '@angular/router/testing';


然后在import[]部分中使用它,如下所示:

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

    }).compileComponents();
  }));

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

在你的情况,如果你不想测试任何路由都不过,你可以通过使用忽略这个错误NO_ERRORS_SCHEMA ,而不是CUSTOM_ELEMENTS_SCHEMA 后者将避免与HTML元素相关的错误,但前者将忽略所有错误,包括未知的绑定属性。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM