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
});
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.