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 '/'
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;
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With