Angular Test Router navigateByUrl
April 23, 2022
On this page we will learn to test Router.navigateByUrl
method.
In our application, we inject
Router
in our component using constructor.
constructor(private bookService: BookService, private router: Router) { }
goToDetail(id: number) { const url = '/view-detail/' + id; this.router.navigateByUrl(url); }
<button (click)="goToDetail(101)" class="detail-button">View Detail</button>
To test
navigateByUrl
, find the steps.
Step-1 : Create spy object.
const routerSpy = jasmine.createSpyObj('Router', ['navigateByUrl']);
TestBed.configureTestingModule({ providers: [{ provide: Router, useValue: routerSpy }] })
const spy = router.navigateByUrl as jasmine.Spy; const navArgs = spy.calls.first().args[0]; expect(navArgs).withContext('should nav to ViewDetailComponent for book detail') .toBe('/view-detail/' + id);
Complete Example
Find the technologies being used in our example.1. Angular 13.1.0
2. Node.js 12.20.0
In our example, we have a button and on the click of the button,
goToDetail()
method is called with an id and this component is navigated to another component using /view-detail/' + id URL. We write a test case to test the navigating URL.
home.component.spec.ts
import { ComponentFixture, TestBed, fakeAsync, waitForAsync, tick } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { Router } from '@angular/router'; import { HomeComponent } from './home.component'; describe('HomeComponent', () => { let component: HomeComponent; let fixture: ComponentFixture<HomeComponent>; const routerSpy = jasmine.createSpyObj('Router', ['navigateByUrl']); beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ providers: [{ provide: Router, useValue: routerSpy }] }).compileComponents().then(() => { fixture = TestBed.createComponent(HomeComponent); component = fixture.componentInstance; }); })); it('should tell ROUTER to navigate when button clicked', fakeAsync(() => { let router = fixture.debugElement.injector.get(Router); let buttonElements = fixture.debugElement.query(By.css('.detail-button')); buttonElements.triggerEventHandler('click', null); tick(); const spy = router.navigateByUrl as jasmine.Spy; const navArgs = spy.calls.first().args[0]; const id = 101; expect(navArgs).withContext('should nav to ViewDetailComponent for book detail') .toBe('/view-detail/' + id); })); });
