Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular unit-testing mock paramMap get

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

like image 524
Sergey Avatar asked Nov 26 '18 11:11

Sergey


People also ask

How do you mock ActivatedRoute?

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 // ...

What is Parammap in Angular?

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() .

What is mocking in unit testing Angular?

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.

How do you test for ActivatedRoute in Angular 6?

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).


1 Answers

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 paramMapin 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.

like image 79
Antoniossss Avatar answered Sep 25 '22 00:09

Antoniossss