4

我正在尝试在我的组件中测试对 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 相关的问题(此处此处)的答案,但无济于事。

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

4

1 回答 1

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();
    });
}));
于 2017-07-03T05:04:29.697 回答