How to mock route.snapshot.params?

本秂侑毒 提交于 2020-03-17 06:51:10

问题


In my Angular 4 component I have something like:

constructor(private route: ActivatedRoute) {
}

ngOnInit() {
  this.myId = this.route.snapshot.params['myId'];
}

And I'm trying to create a mock that suppose to look like follows:

class MockActivatedRoute extends ActivatedRoute {
  public params = Observable.of({ myId: 123 });
}    

My test fails with:

TypeError: Cannot read property 'params' of undefined.

How do I suppose to mock it? Have I misunderstood the proper usage of ActivatedRoute and should better use router.subscribe in my component? I saw some complicated examples where people mocked snapshot itself, however for me it looks overcomplicated.


The test itself is quite simple:

describe('ngOnInit', () => {
it('should set up initial state properly',
  () => {
  const component = TestBed.createComponent(MyComponent).componentInstance;
    component.ngOnInit();
    expect(component.myId).toEqual('123');
  });
});

If I simply change a method under the test to something like follows - the test works:

ngOnInit() {
    //this.myId = this.route.snapshot.params['myId'];
    this.route.params.subscribe(params => {
    this.myId = params['myId'];
    });
}

Obviously I need to mock Activated snapshot, but is there a better approach?


回答1:


Ok, I've found how to mock ActivatedRoute snapshot in the simple way. Something like this works for me:

providers: [MyComponent, {
  provide: ActivatedRoute,
  useValue: {snapshot: {params: {'myId': '123'}}}
}

Thanks :)




回答2:


If using route.snapshot.paramMap.get( 'uuid' ) instead:

import { ActivatedRoute, convertToParamMap } from '@angular/router';

{
    provide: ActivatedRoute, useValue:
        { snapshot: { paramMap: convertToParamMap( { 'uuid': '99-88-77' } ) } }
}



回答3:


There is a basic syntax error in your code

Instead of

this.myId = this.route.snapshot.params['myId'];


Update your code with

this.myId = this.route.snapshot.paramMap.get('myId');


You will be able to successfully mock param now.
I am assuming that you have declared field property myId.



来源:https://stackoverflow.com/questions/46831630/how-to-mock-route-snapshot-params

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!