我正在尝试单元测试一个组件,我正在使用数据解析器类获得'组'数据。下面是它的代码:
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;
}
})
}
}
为了进行测试,我使用'groupsResponse'的模拟数据,如下所示:
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
}
然后我传递这个模拟值ActivatedRoute如下:
let activatedRouteMock: any;
beforeEach(waitForAsync(() => {
activatedRouteMock = {
data: of({groupsResponse: [mockGroupsResponse]})
};
TestBed.configureTestingModule({
imports:[...],
declarations: [GroupsComponent],
providers:[..., {provide: ActivatedRoute, useValue: activatedRouteMock }]
}).compileComponents
解析器的模拟数据被成功读取。然而,我面临的问题是,而试图分配组数组从响应到局部变量。
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; // here, not able to set this.groups array from groupsResponse. (undefined)
}
})
}
}
任何想法我做错了什么嘲弄。在实际情况下,我使用http作为承诺从解析器获取数据,我没有设置数组的任何问题。然而,我的测试不工作
从构造函数中移除API调用,并将它们移动到ngOnInit中。
构造函数只能用于注入依赖项。裁判构造函数在模拟服务准备好之前被触发。