简体   繁体   中英

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

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM