Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Unit Tests - how to mock router.url

I have an angular 6 application and I am trying to unit test a component where I inject the Router. In my ngOnInit method I reference this.router.url and work with it.

So now I am attempting to write a jasmine unit test and I cannot set the router.url property because it "is a constant ot read only property". I am currently mocking the router like this.

mockRouter = jasmine.createSpyObj<Router>("router", ["navigate", "navigateByUrl"]);

What else do I need to set to properly mock the url value in my test?

like image 664
user1247395 Avatar asked Sep 01 '25 01:09

user1247395


1 Answers

Jasmine spy on property should be reasonable solution

spyOnProperty(router, 'url', 'get').and.returnValue('/users');

as recommended here https://stackoverflow.com/a/43793575/11552394

and documented in Jasmine docs https://jasmine.github.io/api/3.4/global.html#spyOnProperty

like image 125
Alex Karamushko Avatar answered Sep 02 '25 18:09

Alex Karamushko