jasmine angular 4 unit test router.url

First you need to mock router in your testing module:

TestBed.configureTestingModule({
  ...
  providers: [
    {
       provide: Router,
       useValue: {
          url: '/path'
       } // you could use also jasmine.createSpyObj() for methods
    } 
  ]
});

You can also change the url in the test and run your tested method:

const router = TestBed.inject(Router);
// @ts-ignore: force this private property value for testing.
router.url = '/path/to/anything';
// now you can run your tested method:
component.testedFunction();

As you mention spyOn doesnt work because it works only for methods/functions. But url is a property.


For people using Angular 9 and above property url is now a readonly property and so spyOnProperty will not work. It's also confusing as you won't get an error, but you won't see any "spying" either.

To solve this, use the following code:

const mockUrlTree = routerSpy.parseUrl('/mynewpath/myattribute');
// @ts-ignore: force this private property value for testing.
routerSpy.currentUrlTree = mockUrlTree;

Thanks to Rob on this post here for the answer:

https://stackoverflow.com/a/63623284/1774291