TypeError:studentsList.forEach不是函数。茉莉花单元测试(角2)
问题描述:
如何使用业力测试茉莉花forEach循环? 分量代码如下: - 在studentsListTypeError:studentsList.forEach不是函数。茉莉花单元测试(角2)
getData(studentsList:any, day:any, game:any){
let strength:any;
let location:string;
if(studentsList){
studentsList.forEach(value => {
strength=value.schedule[day][game].strength;
location=value.schedule[day][game].location;
});
}
}
数据本是: -
(编辑: - 所述数据被更新它看起来像这样)
[{
"activityName": "tournament1",
"schedule": {
"first": {
"Baseball": {
"strength": 23,
"location": "abc"
}
},
"second": {
"Cricket": {
"strength": 20,
"location": "bcd"
}
},
"third": {
"Football": {
"strength": 19,
"location": "cde"
}
}
}
},
{
"activityName": "tournament2",
"schedule": {
"first": {
"Baseball": {
"strength": 23,
"location": "abc"
}
},
"second": {
"Cricket": {
"strength": 20,
"location": "bcd"
}
},
"third": {
"Football": {
"strength": 19,
"location": "cde"
}
}
}
},{
"activityName": "tournament3",
"schedule": {
"first": {
"Baseball": {
"strength": 23,
"location": "abc"
}
},
"second": {
"Cricket": {
"strength": 20,
"location": "bcd"
}
},
"third": {
"Football": {
"strength": 19,
"location": "cde"
}
}
}
}]
这是我试过的测试: -
it('should check getData()',() => {
fixture = TestBed.createComponent(GameComponent);
const app = fixture.debugElement.componentInstance;
const data={
"activityName": "tournament",
"schedule": {
"first": {
"Baseball": {
"strength": 23,
"location": "abc"
}
},
"second": {
"Cricket": {
"strength": 20,
"location": "bcd"
}
},
"third": {
"Football": {
"strength": 19,
"location": "cde"
}
}
}
}
app.getData(data, 'first', 'Baseball');
fixture.detectChanges();
expect(app.location).toContain('abc');
expect(app.location).toContain('bcd');
expect(app.location).toContain('cde');
}
但我一直在为这个forEach不是一个函数。我应该采取其他方式来替代测试中的静态数据?
答
studentsList
是一个对象,但forEach
只存在于数组上。如果这是你想要做的事情,你可以使用for (var key in studentsList)
迭代对象的键。
+0
由于我的问题得到解决通过传递'数据= [{ “activityName”: “比赛”, “时间表”:{ “第一”:{ “棒球”:{ “强度”:23, “位置”: “ABC” } }, “第二”:{ “蟋蟀”:{ “强度”:20, “位置”: “BCD” } } , “第三”:{ “足球”:{ “强度”:19, “location”:“cde” } } } }]'as array – Jia
'forEach'需要数组 –