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 '/'
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;
currentUrlTree
is readonly. The problem is it is now also a getter. The raw value is now buried in another Service that isn't end user accessible –
Chaldron 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
});
I have had to move from some of the suggested solutions used here during my migration to Angular 17. Inside the TestBed Configuration, provide some test routes:
imports: [
RouterTestingModule.withRoutes([
{ path: '', component: YourComponent },
{ path: 'page', component: YourComponent },
{ path: 'page/fail', component: YourComponent },
{ path: 'etc', component: YourComponent },
{ path: '**', redirectTo: '' }
])
]
Then in your actual test, it can be configured as the following:
it('should return true if url ends with page', async () => {
// Arrange
const expected = true;
await component['router'].navigate(['page']);
// Act
const actual = component.isPage();
// Assert
expect(actual).toEqual(expected);
});
This may not be ideal, but now that the properties we have been relying on until now are readonly, I'm not aware of any other path forward for the moment.
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();
cannot assign to 'url' bacause its a constant property
–
Kingfisher © 2022 - 2024 — McMap. All rights reserved.