Error: The studentsList is not iterable. Issue encountered during Jasmine Unit Testing in Angular 2

How can I effectively test the forEach loop in jasmine with karma? Below is the code for the component:

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 within studentsList is as follows:

(Edit:- The data has been updated and appears 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"
            }
        }
    }
}]

Here's the test that I attempted:

it('should validate 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');
}

However, I am consistently receiving a 'forEach is not a function' error. Should I explore another approach instead of using static data in the test?

Answer №1

studentList is actually an object, and the forEach method can only be used on arrays. In this case, you can utilize a for loop like for (var key in studentList) to iterate through the keys of the object instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Comparing the use of jQuery's data() method versus directly accessing attributes with native JavaScript using get

I want to retrieve general information from my website using javascript. I have a few different options available: I could use an html element: <input type="hidden" value="MyValue"/> Another option is to use a custom attribute in an existing h ...

Using Nuxtjs/Toast with personalized image emblems

Would it be possible to include an icon in a toast error message, or is there a need to install another module for this functionality? I am currently using vue and attempting to integrate a component as an icon, but so far without success. this.$toast.er ...

Challenges with unique scrollbar designs and dynamic tab loading using AJAX

Hello to all amazing members of stackoverflow, I'm facing some major challenges getting my custom scrollbar to function properly with ajax-based tabs. Any assistance you can provide would be immensely helpful. I have most of it set up and operational ...

Updating form validation by altering input value

I'm currently utilizing JavaScript regular expressions for form validation in my project. After successfully completing the validation without any errors, upon clicking the submit button, I want the form to be submitted and change the submit value to ...

Retrieve specific information from checkboxes within a form

I'm working on a form that includes multiple checkboxes populated with data from a JSON file using ng-repeat. After submitting the form, I need to retrieve the data from the checked checkboxes. How can I accomplish this in my controller after the form ...

Tips for displaying buttons and images on the same line using CSS

Below is the JavaScript code I am using: $('#needdiv').append('<img src="/images/Connect.png" id="connectimage">' + '</img>' + '<input type="button" id="connect" value=connect >' + '&l ...

What is the method for setting a default image to be preloaded in filepond?

Currently, I am working on a Laravel view for editing a record which includes an associated image. My goal is to have the image preloaded inside the input file so that when you submit the form, the same image is sent or you can choose to change it. // Con ...

In vuex, dynamic modules share common data and do not have unique data

Currently, I am facing an issue with an asynchronous API call that returns an array of objects. After receiving this data, I map it to dynamically registered modules in my store. The process looks something like this: dispatch // prior to this dispatch, ...

Comparison of Node.js and Express.js APIs for handling responses

Both Node.js and Express.js have their own unique response APIs. Interestingly, there are some similarities between the two, such as: Node.js: response.write(chunk[, encoding][, callback]) Express.js: res.attachment([filename]) res.download(path [, ...

The value is undefined until a new Resource object is pushed with the item

I've encountered an issue while testing a factory and I can't seem to find anyone else with the same problem. Can someone help me figure out what's causing this strange error? TypeError: 'undefined' is not a function (evaluating & ...

Sending information to @select of multiselect in Vue.js - vue-multiselect

I'm currently working on passing a parameter to the @select event function in Vue.js HTML <template> <div class="container"> <div v-for="(billItem, k) in billItems" :key="k" > <div class=&q ...

Unique ways to serialize an HTML element efficiently: JavaScript tricks

Is there a way to store a reference of an HTML tag for future use? For instance, if I click on a div and save a pointer to that div in JavaScript, is it possible to serialize this pointer and then de-serialize it to use in another part of the web applicat ...

Is the routing malfunctioning and causing the page to appear blank?

I am currently attempting to implement routing in the code below. Despite changes in the URL, the page remains empty and there are no errors shown in the console. html <div ng-app="myApp"> <ul> <li><a href="#!/ ...

Providing a callback function along with the specific execution context for it to be executed

myFn is a function that executes an asynchronous task and triggers the callback upon successful completion. SearchController.prototype.show = function (query) { this.searchService.myFn(arg1, this.myCallback); //I want to preserve the reference of `th ...

Is it possible for a function within a nodejs module to be defined but display as undefined upon access?

I am currently developing a Discord bot using NodeJS and TypeScript, and I'm facing an issue while trying to import custom modules in a loop with the following code: const eventFiles = fs.readdirSync("./src/events/").filter((file: string) =& ...

What are the steps to make a div with no content inside?

Presently, I am dealing with 2 overlapping transparent div's each containing unique buttons and functionalities in the following manner: .item1{ height:10rem; width:10rem; position:absolute; border:0.5rem solid red; background-color:trans ...

Utilize .GLB and Blender file formats within a Gridsome project developed with Vue.js

I am working on a project using Three.js in Gridsome, but I am facing difficulties importing .glb files (3D models) with GLTFLoader. While Gridsome recognizes img (png/jpg) or .js files stored in src/assets, it does not seem to support glb files. This is ...

Simulated web server for testing with Jest

Can I ask a unique question? I have a tool for extracting data from webpages directly, not through APIs. I want to create end-to-end tests for this tool using the Jest library, but I need to ensure the web pages I'm referencing remain consistent. It&a ...

Concealing website links in the browser's address bar

Running my own website on a personal server with Ubuntu server, I noticed that my public IP address is displayed in the status bar when visitors browse my site or hover over links. Even after purchasing a domain name from godaddy, I couldn't find an o ...

What could be causing ng-repeat to malfunction?

My ng-repeat is not working with the table - only the header part is being displayed in the output. I have checked my binding and it seems to be correct, but I know I am missing something. Can someone please help me figure out what I am doing wrong? JAVA ...