Attempting to conduct unit testing on a component involving the retrieval of 'Groups' data through a data resolver class. Below is the corresponding code:
export class GroupsComponent implements OnInit, OnDestroy {
group: IGroup;
groups: IGroup[];
constructor(
private activatedRoute: ActivatedRoute,
private titleService: Title,
private userService: GroupsService
){
this.titleService.setTitle('Home | Groups');
this.groups = [];
this.groupsComponentDataSubscription = this.activatedRoute
.data
.subscribe(
data => {
if(data['groupsResponse']){
this.groupsResponse = data['groupsResponse'] as IGroupsResponse;
this.groups = this.groupsResponse.groups;
}
})
}
}
For testing purposes, using mock data for 'groupsResponse' as illustrated below:
let mockGroups: IGroup[] = [{
groupName: "testGroup1",
description : "group1 detail",
apiRoles: ["foo", "bar", "monitoring"],
kafkaClusters: [{
clusterId: "cluster1",
topics: ["foo", "bar"],
connectClusters:[{
clusteId: "testCluster1",
connectorNames: ["foo", "bar"]
}]
}]
},
groupName: "testGroup2",
description : "group2 detail",
apiRoles: ["foo", "bar", "foobar"],
kafkaClusters: [{
clusterId: "cluster2",
topics: ["foo", "bar"],
connectClusters:[{
clusteId: "testCluster2",
connectorNames: ["foo", "bar"]
}]
}]
}
]
let mockGroupsResponse: IGroupsResponse = {
groups: mockGroups
}
Subsequently, the mock value is passed for ActivatedRoute as shown:
let activatedRouteMock: any;
beforeEach(waitForAsync(() => {
activatedRouteMock = {
data: of({groupsResponse: [mockGroupsResponse]})
};
TestBed.configureTestingModule({
imports:[...],
declarations: [GroupsComponent],
providers:[..., {provide: ActivatedRoute, useValue: activatedRouteMock }]
}).compileComponents
Though the mock data for resolver is successfully read, the issue arises when attempting to assign the groups array from the response to the local variable.
constructor(
private activatedRoute: ActivatedRoute,
private titleService: Title,
private userService: GroupsService
){
...
....
this.groupsResponse = data['groupsResponse'] as IGroupsResponse; // groupsResponse is assigned as mock data -- console.log -> [{ groups: [object], [object]]
this.groups = this.groupsResponse.groups; // encountered difficulty setting this.groups array from groupsResponse. (undefined)
}
})
}
}
Seeking insights on potential errors within the mock setup. While situations involving data retrieved from the resolver using http as Promise function smoothly, the test scenario proves to be problematic.