Angular Test Router navigateByUrl

By Arvind Rai, 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) { } 
For the demo, we have a method to navigate to other component.
goToDetail(id: number) {
     const url = '/view-detail/' + id;
     this.router.navigateByUrl(url);
} 
On the click of the button, we call the above method.
<button (click)="goToDetail(101)" class="detail-button">View Detail</button> 
Testing

To test navigateByUrl, find the steps.
Step-1 : Create spy object.
const routerSpy = jasmine.createSpyObj('Router', ['navigateByUrl']); 
Step-2: Configure testing module.
TestBed.configureTestingModule({
   providers: [{ provide: Router, useValue: routerSpy }]
}) 
Step-3 : Now test the navigation URL.
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);
  }));

}); 
Find the print screen of the output.
Angular Test Router navigateByUrl

Reference

Component testing scenarios

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us