使用 routerLink 的 Angular 2 单元测试组件

标签 angular typescript angular2-routing angular2-testing

我正在尝试使用 angular 2 final 测试我的组件,但我收到错误消息,因为该组件使用了 routerLink 指令。我收到以下错误:

Can't bind to 'routerLink' since it isn't a known property of 'a'.

这是ListComponent模板的相关代码

<a 
  *ngFor="let item of data.list" 
  class="box"
  routerLink="/settings/{{collectionName}}/edit/{{item._id}}">

这是我的测试。

import { TestBed } from '@angular/core/testing';

import { ListComponent } from './list.component';
import { defaultData, collectionName } from '../../config';
import { initialState } from '../../reducers/reducer';


const data = {
  sort: initialState.sort,
  list: [defaultData, defaultData],
};

describe(`${collectionName} ListComponent`, () => {
  let fixture;
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        ListComponent,
      ],
    }).compileComponents(); // compile template and css;
    fixture = TestBed.createComponent(ListComponent);
    fixture.componentInstance.data = data;
    fixture.detectChanges();
  });

  it('should render 2 items in list', () => {
    const el = fixture.debugElement.nativeElement;
    expect(el.querySelectorAll('.box').length).toBe(3);
  });
});

我看了几个类似问题的答案,但找不到适合我的解决方案。

最佳答案

您需要配置所有路由。对于测试,您可以使用 @angular/router/testing 中的 RouterTestingModule,而不是使用 RouterModule,您可以在其中设置一些模拟路线。您还需要从 @angular/common 为您的 *ngFor 导入 CommonModule。下面是一个完整的通过测试

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { By } from '@angular/platform-browser';
import { Location, CommonModule } from '@angular/common';
import { RouterTestingModule } from '@angular/router/testing';
import { TestBed, inject, async } from '@angular/core/testing';

@Component({
  template: `
    <a routerLink="/settings/{{collName}}/edit/{{item._id}}">link</a>
    <router-outlet></router-outlet>
  `
})
class TestComponent {
  collName = 'testing';
  item = {
    _id: 1
  };
}

@Component({
  template: ''
})
class DummyComponent {
}

describe('component: TestComponent', function () {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        CommonModule,
        RouterTestingModule.withRoutes([
         { path: 'settings/:collection/edit/:item', component: DummyComponent }
        ])
      ],
      declarations: [ TestComponent, DummyComponent ]
    });
  });

  it('should go to url',
    async(inject([Router, Location], (router: Router, location: Location) => {

    let fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();

    fixture.debugElement.query(By.css('a')).nativeElement.click();
    fixture.whenStable().then(() => {
      expect(location.path()).toEqual('/settings/testing/edit/1');
      console.log('after expect');
    });
  })));
});

更新

另一种选择,如果您只想测试路线是否正确呈现,而不尝试导航...

您只需导入 RouterTestingModule 而无需配置任何路由

imports: [ RouterTestingModule ]

然后只需检查链接是否使用正确的 URL 路径呈现,例如

let href = fixture.debugElement.query(By.css('a')).nativeElement
    .getAttribute('href');
expect(href).toEqual('/settings/testing/edit/1');

关于使用 routerLink 的 Angular 2 单元测试组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39577920/

相关文章:

具有功能 RouterLink 的 Angular2 动态 HTML

javascript - Angular 2 : How do I get params of a route from outside of a router-outlet

Angular2 router.navigate刷新页面

javascript - Ionic 2 Facebook 风格页脚栏

angular - 类型 LoginPage 是两个模块声明的一部分

java 休息调用获取 url net::ERR_FAILED

javascript - 类型 'string' 无法分配给类型 '"string"| "string"' 尝试调用对象文字

angular - RxJS Observables 数组以及要保存的附加数据

angular - *ngIf 带有多个异步管道变量

javascript - Angular 2 发送空帖子