How to test the forEach loop in jasmine using karma?? The component code is as follows:-
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;
});
}
}
the data present in studentsList is:-
(Edit:- the data is updated it looks like this)
[{
"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"
}
}
}
}]
This is the test that I tried:-
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');
}
But I keep on getting this forEach is not a function. Instead of giving static data in the test should I go for some other way?
studentsList
is an object, but forEach
only exists on arrays. You can use for (var key in studentsList)
to iterate the keys of the object if that's what you'd like to do.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.