【发布时间】:2021-10-29 13:43:19
【问题描述】:
我正在尝试对使用数据解析器类获取“组”数据的组件进行单元测试。这是它的代码。
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 作为 Promise 从解析器获取数据的实际情况下,设置数组没有任何问题。但是,我的测试不起作用
【问题讨论】:
标签: angular typescript unit-testing jestjs jasmine