How to write unit testing for router.url in angular 2

Viewed 1488

Please help to write unit testing on router.url usging angular 2. Please have a look at the below code to understand my query.

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
    selector: 'app-about',
    templateUrl: './app-about.component.html',
    styleUrls: ['./app-about.component.scss']
})
export class AboutComponent implements OnInit {
    constructor(private router: Router) {
        if (this.router.url.includes('home')) {
            ...some functions
        }
    }
}
1 Answers

In my unit test, I don't not try to modify "router.url" but I navigate to the wanted url.
To do this I use the Angular's RouterTestingModule:

TestBed.configureTestingModule({
  declarations: [MyComponentToTest, DummyComponent],
  providers: [Location],
  imports: [RouterTestingModule.withRoutes([{ path: 'search', component: DummyComponent },
    { path: 'dashboard', component: DummyComponent }])]
  }).compileComponents();

With Dummy component:

@Component({ template: '' })
class DummyComponent { }

It sets up the router with two mocked routes.
Then, in the test I recover the router:
const router = TestBed.get(Router);
And navigate to the wanted url:
router.navigate(['/search']);
You might need to do a fixture.detectChanges(); to refresh the component before any other actions.

Related