8

How do I mock router.url in angular 4 unit testing?

I use router.url in ngOnint in my component but in my test the value for router.url is '/'

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sarat
  • 111
  • 1
  • 5

3 Answers3

17

In Angular v9 Router.url is a readonly getter property. You can force the private property value to set the url property:

    const mockUrlTree = router.parseUrl('/heroes/captain-marvel');
    // @ts-ignore: force this private property value for testing.
    router.currentUrlTree = mockUrlTree;
Rob
  • 3,687
  • 2
  • 32
  • 40
  • This is the only solution that worked for me, when both, RouterTestingModule and router.url are used in unit tests – Alex Ryltsov Jan 15 '21 at 02:43
  • 2
    This answer needs more upvotes if you are using a later version of Angular then the other answers will not work. – PeterS Jan 26 '21 at 11:09
3

you could use jasmine spyObj. In you TestBed:

providers:[
 {
 provide: Router,
 usevalue: jasmine.createSpyObj('Router',['methodOne','methodTwo]),
 },
],

in beforeEach:

router = fixture.debugElement.injector.get(Router);

in the test:

it('should...', ()=> {
 (router.methodOne as Spy).and.returnValue(whateverValue)// if you wanna mock the response
});
kodeaben
  • 1,829
  • 3
  • 24
  • 33
-2

This sounds like a solution jasmine angular 4 unit test router.url

const router = TestBed.get(Router);
router.url = '/path/to/anything';
// now you can run your tested method:
component.ngOnint();
Mohamed Farouk
  • 1,089
  • 5
  • 10