Search code examples
angulartestingjasminekarma-jasminealert

Karma-Jasmine How to test in angular a Router component


I want to test this header component but I don't know how to do it, Im working with angular, just want to test a router function

This is the html

<header class="site-header">
  <nav class="navbar-home">
    <a (click)="routerTo('/home')">CIUDADELA </a> |
    <a (click)="routerTo('/request')">Solicitudes</a> |
    <a (click)="routerTo('/materials')">Materiales</a> |
  </nav>
</header>

And this is the header.component.ts

import { Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent{

  constructor(
    private router: Router
  ) { }

  routerTo(link : string): void {
    this.router.navigate([link]);
  }

}


And this is what coverage says that i need to test

enter image description here


Solution

  • I would write a test like this to cover the call to router:

    it('navbar-home item should call router.navigate',() => {
         const router= TestBed.inject(Router)
         spyOn(router, 'navigate')
         const firstLink = fixture.debugElement.query(By.css('.navbar-home')).children[0]
         firstLink .triggerEventHandler('click', '/home');
         fixture.detectChanges()
         expect(router.navigate).toHaveBeenCalledWith(['/home']);
      });
    

    same way you cann check call to you're components function.

    you need to provide the router in your test setup