I've component which represents an item from a list and to get this item I use this.route.snapshot.paramMap.get('id')
. How do I mock this? I've tried
providers: [
{
provide: ActivatedRoute,
useValue: { snapshot: { params: convertToParamMap({ id: '1' }) } }
}
]
But this results in
TypeError: Cannot read property 'get' of undefined
You are providing
{ snapshot: { params: convertToParamMap({ id: '1' }) }
so its snapshot.params
while you try ti access it via this.route.snapshot.paramMap
as you can see, there is no paramMap
in your mock.
The fact that you are providing object as "value" does not mean that this object will automatically become instance of ActivatedRoute
. Its just what you defined - plain object. There is no runtime type controll, so this is allowed.
You can simply provide partial implementation, something like
useValue: { snapshot: { paramMap: {get:(id:number)=>{id:1}}}}
or make getter for this property in your component - this will allow you to spy
on that getter call, intercept it and return required value.
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.