Testing a function in Angular using Karma and Jasmine

I am facing an issue while testing a method in Angular using Jasmine/Karma. The error message I keep encountering is:

TypeError: undefined is not iterable (cannot read property Symbol (Symbol.iterator))

This is how I created the method:

  myMethod(locs: MyCustomType1[], clocs: MyCustomType2[]) {
    clocs = clocs
      .filter(cl => cl !== null && cl.l_ids !== null);
    locs = locs
      .filter(l => l !== null && l.id !== null);

    clocs.forEach(
      cl => {
        cl['l_names'] = [];
        locs.forEach(
          l => {
            if (cl.l_ids.includes(l.id)) {
              clocs['l_names'].push(l.name);
            }
          }
        );
      }
    );
  }

Here is the current framework of my test:

  describe('#MyMethod', () => {
    beforeEach(() => {
      component.clocs = mockClocs;
      component.locs = mockLocs;
      component.myMethod(mockLocs, mockClocs);
    });
    describe('myMethod()', () => {
      it('Should check if clocs and locs arrays are defined', () => {
        expect(component.clocs).toBeDefined();
        expect(component.locs).toBeDefined();
      });

      it('Should verify that clocs array contains "Location2" and "Location3" with locationIds 2, 3', () => {
        expect(component.clocs[1]['l_names'].includes('Location2')).toBeTruthy();
        expect(component.clocs[1]['l_names'].includes('Location3')).toBeTruthy();
      });
    });
  });

The error mentioned above persists for every expect() statement within the it() block. Although the logged arrays display the correct values, the expect() function returns undefined. What could be causing this issue?

Answer №1

To compare values, you can utilize the .toEqual() method.

      it('Ensure that the clocs array contains "Location2" and "Location3" with the corresponding locationIds of 2 and 3', () => {
        expect(component.clocs).toEqual([{l_names: ['Location2', 'Location3']}]);
      });

Answer №2

To ensure that my arrays were properly filled within the beforeEach method, I called ngOnChanges(). My solution looked like this:

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    component.clocs = mockClocs;
    component.locs = mockLocs;
    component.myMethod(mockLocs, mockClocs);
    component.ngOnChanges();
    fixture.detectChanges();
  });

In addition, I removed an unnecessary describe block.

I hope this answer proves useful. Feel free to share any suggestions for improvements you may have :)

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

Heroku build is reporting that it cannot locate the `@types` in the package.json file

Encountered Heroku Build Error - TSError: ⨯ Struggling to compile TypeScript: - src/server.ts(1,38): error TS7016: File declaration for module 'express' not found. '/app/node_modules/express/index.js' is implicitly of type 'any&a ...

Angular's browser animation feature allows for smooth slide-up animations from the bottom

I have been experimenting with creating a simple animation, and it's working, but in the opposite direction of what I intended. I want the div to open from bottom to top and close from top to bottom. Here is my animation code in Angular: animations: ...

Ensure that the ngOnChange is triggered after the BehaviorSubject emits a true value twice

I am currently developing an Angular 5 application. One of the components in my project is a dropdown component ( containing the following code in the html file, dropdown.component.html <p-dropdown [options]="data" [(ngModel)]="selectedFilterValue" pl ...

Shifting attention to an angular 6 form field

I am developing an application in Angular which involves creating, reading, updating, and deleting user information. I have a requirement for the username to be unique and need to display an error message if it is not unique, while also focusing on the use ...

I encountered a TypeError when attempting to load MDX in Next.js with the mdx-js/react library

My Goals and Assumptions for the Project Please note that this question has been translated using Deepl Translations. I aim to integrate mdx-js/react into Next.js for loading mdx files. Environment Details: Operating System: macOS Big Sur Node Version: ...

A tip for transferring the value of a binding variable to a method within the template when the button is clicked

I am currently exploring the concept of binding between parent and child components using @Input, @Output, and EventEmitter decorators. This is demonstrated in the HTML snippet below: <h1 appItemDetails [item]="currentItem">{{currentItem}}& ...

Exploring PrimeNG's method for expanding and collapsing groups

I'm attempting to incorporate two buttons that can be used to either expand or collapse all the groups in my code utilizing primeNG. Below is the functioning code: PLUNKER <p-dataTable [value]="data" sortField="room" rowGroupMode="subheader" grou ...

Displaying images in Ionic from a JSON URL source

I am having trouble getting an image from a JSON to display on an Ionic card. Although I can see the JSON response in the console log, the image is not showing up on the card, leaving it blank. It seems like I'm making a mistake in the HTML code. Any ...

What is the reason for Akita statestore returning an empty entity instead of the updated entity?

I'm utilizing Akita as the state management solution for my Angular application. Currently, I can retrieve data from a backend server and populate my store successfully (the data is displayed in components). However, when attempting to update an enti ...

import component dynamically from object in Next.js

Currently, I have a collection of components that I am aiming to dynamically import using next/dynamic. I'm curious if this is achievable. Here's the object in interest: // IconComponents.tsx import { Tick, Star } from 'components ...

Using ngIf to locate a substring

<ul class="list-group" *ngFor="let head of channelDisplayHeads"> <li class="list-group-item" *ngFor="let channel of channelList" ngIf="channel.channel.indexOf('head') === 1"> <strong>{{ head }}</strong> ...

Using RxJS and the combineLatest function can be hit or miss in terms of reliability

When you call this function multiple times with the values of observables obs1 and obs2 being the same each time, the returned array may not always be the same. getUniqueProducts(obs1: Observable<any>, obs2: Observable<any>): Observable<any& ...

Issues encountered when using PrimeNG tree select component with filter functionality

After successfully implementing the new primeng treeselect component with selection mode as "checkbox," I encountered an issue when trying to add a [filter]="true" as shown in the PrimeNG demo. <p-treeSelect [(ngModel)]="selectedNode1" [options]="nodes1 ...

Arranging an array of objects in typescript with elements implicitly having an undefined type

Currently, I am facing a challenge where I need to sort an array of objects within a function. The catch is that the function receives the key as a parameter, making it unknown: export interface ProductsList { id: boolean nome: string qtde: number ...

Struggling to modify a string within my React component when the state is updated

Having a string representing my file name passed to the react-csv CSVLink<> component, I initially define it as "my-data.csv". When trying to update it with data from an axios request, I realize I may not fully understand how these react components w ...

Unable to assign a value to the HTMLInputElement's property: The input field can only be set to a filename or an empty string programmatically

When attempting to upload an image, I encountered the error message listed in the question title: This is my template <input type="file" formControlName="avatar" accept=".jpg, .jpeg .svg" #fileInput (change)="uploa ...

When utilizing the navigation.navigate function, react-navigation v6.0 may present an error message

The Challenge I'm Dealing With One issue I encountered is when I use navigation.navigate('XXXPage'), react-navigation version 6.0 displays the following error message. Argument of type 'string' is not assignable to parameter of ty ...

Can someone guide me on capturing an API response error using observables?

Currently working with Angular 4, my API call is functioning properly, returning the expected JSON for successful responses. However, in case of an error response, instead of receiving a JSON response as expected, I end up with a 404 HTML page (which is no ...

No members were exported by the module, please export an interface

I encountered this error: "/Users/robot/code/slg-fe/src/app/leaderboards/leaderboards.component.ts (2,10): Module '"/Users/robot/code/slg-fe/src/app/leaderboards/leaderboard"' has no exported member 'Leaderboard'. This is what my le ...

Tour Of Heroes offers a unique and versatile http create feature

I am currently making my way through the Tour of Heroes tutorial and finding it quite enjoyable. Everything is functioning properly, except for one aspect that has me puzzled - the http adding a hero feature. It seems to automatically know what id to ass ...