2017-01-22 85 views
4

我試圖測試上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)的答案,但無濟於事。

關於我在做什麼錯的任何想法?

回答

2

如果您使用外部模板,我建議您創建組件異步。

我建議的第二件事是嘗試使用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(); 
    }); 
}));