在Angular2组件中对RouterLink进行单元测试

时间:2017-01-22 16:34:34

标签: angular routerlink

我正在尝试在我的组件中测试对routerLink的点击:

  <div class="side-menu-boards-container">
    <ul class="side-menu-boards-list">
      <li *ngFor="let board of boards">
        <a [routerLink]="['/board', board.id]">{{board.name}}</a>
      </li>
    </ul>
  </div>

使用此测试:

it('should navigate to correct board url',
    async(inject([Location], (location: Location) => {
      let nativeElement = fixture.nativeElement;
      let link = nativeElement.querySelector('.side-menu-boards-list li a');
      link.click();

      fixture.whenStable().then(() => {
        expect(location.path()).toEqual('/board/1');
      });    
})));

但我的期望是失败,并显示以下消息:Expected '/' to equal '/board/1'

这是我的测试设置:

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

import { SideMenuComponent } from './side-menu.component';
import { BoardComponent } from '../board/board.component';
import { BoardMenuItem } from './models/board-menu-item';

describe('SideMenuComponent', () => {
  let component: SideMenuComponent;
  let fixture: ComponentFixture<SideMenuComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [SideMenuComponent, BoardComponent],
      schemas: [NO_ERRORS_SCHEMA],
      imports: [RouterTestingModule.withRoutes([
        { path: 'board/:id', component: BoardComponent }
      ])]
    })
      .compileComponents();
  });

我已经按照其他两个与SO相关的问题(herehere)的答案,但无济于事。

关于我做错什么的任何想法?

1 个答案:

答案 0 :(得分:3)

如果您使用外部模板,我建议您创建组件异步。

我建议的第二件事是尝试使用RouterTestingModule.withRoutes(<your routes module>)来测试路由器。

不要忘记初始导航。

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports:[RouterTestingModule.withRoutes(routes),
               <Another Modules>, 
                ],
      declarations: [ <your component>],
      providers: [<Services which you have injected inside of your constructor>]
    })
    .compileComponents()
    .then(() =>{
          fixture = TestBed.createComponent(<your component>);
          component = fixture.componentInstance;
          router = TestBed.get(Router);
          location = TestBed.get(Location);
          debugComponent = fixture.debugElement;
          //initial navigation
          router.initialNavigation();
    });
}));