angular - 将数组分配给具有 Mock 数据的另一个数组时出现角度未定义错误
问题描述
我正在尝试对使用数据解析器类获取“组”数据的组件进行单元测试。这是它的代码。
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 从解析器获取数据的实际情况下,设置数组没有任何问题。但是,我的测试不起作用
解决方案
从构造函数中移除 API 调用并将它们移动到 ngOnInit 中。
构造函数应该只用于注入依赖。Ref 构造函数在你的模拟服务准备好之前被触发。
推荐阅读
- javascript - Angular 2 - 创建指令
- javascript - doPost() 可以自己运行吗?
- php - Laravel 背包权限播种“角色不存在”
- java - REST-assured 3.0.0 和 Java 11 的 java.lang.NoClassDefFoundError(Java 8 未观察到)
- javascript - 视频大小和 WebRTC 的问题
- python - 从表中垂直读取抓取的数据,而不是水平读取 Python
- image-processing - 使用 graphicsmagick 裁剪可变宽度框架
- node.js - 从多个视频文件到单个输出
- sql - 如何选择与列表中所有值匹配的值?
- elasticsearch - Kibana - 日志分析 - 查找唯一事务号