Angular 6 - how to mock router.events url response in unit test Angular 6 - how to mock router.events url response in unit test typescript typescript

Angular 6 - how to mock router.events url response in unit test


It can be as simple as:

TestBed.configureTestingModule({  imports: [RouterTestingModule]}).compileComponents()    ...    const event = new NavigationEnd(42, '/', '/');(TestBed.inject(Router).events as Subject<Event>).next(event);


Here is the answer I came up with. I think I just didn't extend the first approach (above) far enough:

import { of } from 'rxjs';import { NavigationEnd, Router } from '@angular/router';providers: [    {      provide: Router,      useValue: {        url: '/non-pdp/phases/8',        events: of(new NavigationEnd(0, 'http://localhost:4200/#/non-pdp/phases/8', 'http://localhost:4200/#/non-pdp/phases/8')),        navigate: jasmine.createSpy('navigate')      }    }]


Thought this might help...have a footer component with routerLinks in the template. Was getting the root not provided error....had to use a "real" router...but have a spied variable..and point the router.events to my test observable so I can control nav events

export type Spied<T> = { [Method in keyof T]: jasmine.Spy };describe("FooterComponent", () => {   let component: FooterComponent;   let fixture: ComponentFixture<FooterComponent>;   let de: DebugElement;   const routerEvent$ = new BehaviorSubject<RouterEvent>(null);   let router: Spied<Router>; beforeEach(async(() => {    TestBed.configureTestingModule({        providers: [provideMock(SomeService), provideMock(SomeOtherService)],        declarations: [FooterComponent],        imports: [RouterTestingModule]    }).compileComponents();    router = TestBed.get(Router);    (<any>router).events = routerEvent$.asObservable();    fixture = TestBed.createComponent(FooterComponent);    component = fixture.componentInstance;    de = fixture.debugElement;}));// component subscribes to router nav event...checking url to hide/show a linkit("should return false for showSomeLink()", () => {    routerEvent$.next(new NavigationEnd(1, "/someroute", "/"));    component.ngOnInit();    expect(component.showSomeLink()).toBeFalsy();    fixture.detectChanges();    const htmlComponent = de.query(By.css("#someLinkId"));    expect(htmlComponent).toBeNull();});