Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 - router.url unit testing

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

like image 886
Sarat Avatar asked Sep 18 '17 05:09

Sarat


2 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;
like image 170
Rob Avatar answered Sep 22 '22 22:09

Rob


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
});
like image 38
methgaard Avatar answered Sep 22 '22 22:09

methgaard