Home > Back-end >  Karma-Jasmine How to test in angular a Router component
Karma-Jasmine How to test in angular a Router component

Time:01-21

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

CodePudding user response:

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

  •  Tags:  
  • Related