4

I am trying to test a click on a routerLink in my component:

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

using this test:

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

but my expect is failing with the following message: Expected '/' to equal '/board/1'

Here is my test setup:

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

I 've already followed the answers from two other SO related questions (here and here) but to no avail.

Any ideas on what am i doing wrong?

Community
  • 1
  • 1
Fjut
  • 1,314
  • 12
  • 23

1 Answers1

3

I suggest you create your component async if you are using external templates.

The second thing I would suggest is to try to use RouterTestingModule.withRoutes(<your routes module>) for testing of router.

And don't forget initial Navigation.

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();
    });
}));
Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
MikBTC
  • 137
  • 1
  • 4