Angular 4 - router.url unit testing

Viewed 6277

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 '/'

3 Answers

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;

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();
Related