1

I am trying to mock the data router snapshot using generic class where we can add data dynamically instead adding data manually. I am able to mock data but it will be hardcoded in the provider section which I dont want.

Is there any reference material for the same ?

Rahul Shukla
  • 646
  • 6
  • 19

2 Answers2

1

if testing is the case, this is my offer:

beforeEach(async(() => {
    TestBed.configureTestingModule({
        imports: [
            MdToolbarModule,
        ],
        providers: [
            {
                provide: Router,
                useClass: MockRouter,
            },
            {
                provide: ActivatedRoute,
                useValue: {
                    data: {
                        subscribe: (fn: (value: Data) => void) => fn({
                            company: COMPANY,
                        }),
                    },
                    params: {
                        subscribe: (fn: (value: Params) => void) => fn({
                            tab: 0,
                        }),
                    },
                    snapshot: {
                        url: [
                            {
                                path: 'foo',
                            },
                            {
                                path: 'bar',
                            },
                            {
                                path: 'baz',
                            },
                        ],
                    },
                },
            },
        ],
    })
    .overrideComponent(ConversationsComponent, {
        set: {
            template: '',
        }
    });
}));
Mahdi Zarei
  • 5,644
  • 7
  • 24
  • 54
  • Thanks for reply, but it still hard coding of "usevalue". Facing this issue since wanted to make this as a class where it can be dynamically assigned values – Rahul Shukla May 05 '21 at 19:39
  • as far as I know testing process always runs under a certain state and the input values are hardcoded. – Mahdi Zarei May 05 '21 at 19:45
  • I guess [`convertToParamMap`](https://stackoverflow.com/a/52895293/23118) would avoid some of that boilerplate. – hlovdal Nov 05 '21 at 09:07
1

You can create a mockActivateRoute class and add the below methods :

public class mockActivateRoute {

setParams(params){

} 
setSnapshotData(data){

}
setQueryParams(params){

}

getParams(){
}

getSnapshotData(){

}

getQueryParams(){

}

}

Then in your method constructor you can use the above class :

provide: ActivatedRoute,
useValue: mockActivateRoute 

Follow this article for more in depth information https://semaphoreci.com/community/tutorials/testing-routes-in-angular-2