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
It is pretty straightforward to mock the ActivatedRoute in the User component test file. All we have to do is to edit the providers list as follows: beforeEach(async(() => { TestBed. configureTestingModule({ declarations: [ UserComponent ], imports: [ RouterTestingModule, HttpClientTestingModule // ...
ParamMaplinkA map that provides access to the required and optional parameters specific to a route. The map supports retrieving a single value with get() or multiple values with getAll() .
A mock component in Angular tests can be created by MockComponent function. The mock component respects the interface of its original component, but all its methods are dummies. To create a mock component, simply pass its class into MockComponent function.
Test Cases for ActivatedRoute it('getDataByNameAndID test case ', () => {route.snapshot.params.id = '2';route.snapshot.params.name = 'testParamChanged';fixture = TestBed. createComponent(MyComponent);component = fixture. componentInstance;fixture. detectChanges();expect(component.name).
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.
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