How to resolve the error "Encountered 'is not iterable' in afterAll block of Angular test using Karma and Jasmine"

I encountered an issue while running Karma tests for Angular. The error message I received was:

  An error was thrown in afterAll
  TypeError: data.data is not iterable

Below is the service that I am trying to test:

getData(): Observable<RealDataModel> {
    return this.http.get<DataResponseModel>('my-url')
      .pipe(
        map((data: DataResponseModel) => (
          { books: [...data.data] }
        ))
      );
}

The response from my GET request looks like this (DataResponseModel):

{
    data: [{...}]
}

However, I need to transform it into a RealDataModel object like this:

export class RealDataModel {
  books: [{...}];
  // Other info that I put using .map
}

Here is the test code where I tried adding verify and resetTestingModule in an attempt to resolve the issue, but without success:

describe('DataService', () => {
  let service: DataService;
  let httpTestingController: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ]
    });
    service = TestBed.inject(DataService);
    httpTestingController = TestBed.inject(HttpTestingController);
  });

  afterEach(() => {
    httpTestingController.verify();
  });

  afterAll(() => {
    TestBed.resetTestingModule();
  });

  it('should be created', () => {
    expect(service).toBeTruthy();
  });

  it('should make a call to /my-url', () => {
    const mockResponse: RealDataModel = {
      books: [{...}]
    };

    service.getData().subscribe(data => {
      expect(data).toEqual(mockResponse);
    });

    const testReq = httpTestingController.expectOne('/my-url');

    expect(testReq.request.method).toEqual('GET');
    testReq.flush(mockResponse);
  });

});

Answer №1

After updating from version 2 to version 18 of puppeteer, the problem was successfully resolved in my situation.

Answer №2

I'm encountering resetTestingModule for the first time, I'm not sure if it's necessary.

Your answer seems a bit off to me.

Perhaps consider trying this instead:

  it('should make a call to /my-url', () => {
    const mockResponse: RealDataModel = {
      // Change 'books' to 'data' here
      data: [{...}] 
    };

    service.getData().subscribe(data => {
      expect(data).toEqual(mockResponse);
    });

    const testReq = httpTestingController.expectOne('/my-url');

    expect(testReq.request.method).toEqual('GET');
    testReq.flush(mockResponse);
  });

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

Running unit tests to verify that the ng-if divs are properly displaying

Inspired by this particular question, I have implemented a method to test the correct display of ng-if tagged divs using Karma instead of Protractor: var element; beforeEach(inject(function ($rootScope, $templateCache, $compile) { scope = $rootScope.ne ...

Trigger parent Component property change from Child Component in Angular2 (akin to $emit in AngularJS)

As I delve into teaching myself Angular2, I've encountered a practical issue that would have been easy to solve with AngularJS. Currently, I'm scouring examples to find a solution with Angular2. Within my top-level component named App, there&apos ...

Utilizing a customized TypeScript Rest Client from Swagger in Angular 2

In my current project, I am developing a Meteor web application using Angular 2 and TypeScript. To interact with a REST API, I have utilized Swagger Codegen to generate client code. However, I am facing a challenge as there are no example implementations a ...

Guidelines for creating a rectangular selection tool in Angular 2+ to choose multiple items

Hello, I am interested in learning how to draw a rectangle to select multiple items using Angular 2+. I currently have a working Plunker example where I would like to implement the ability to select items by drawing a rectangle similar to this jsfiddle I ...

Unlocking the Power of Asynchronous Data in Angular's Dynamic Form Patterns

Utilizing the dynamic form pattern in Angular has been incredibly helpful for our team. By defining our controls in ngOnInit, the form is dynamically constructed based on our needs. However, we've encountered a challenge with forms that require initia ...

Creating dynamic checkboxes in Angular4 and binding them to an array of IDs

Hey there developers, I've been encountering an issue while trying to bind my dynamically generated checkboxes to an array in my project. In my users.template.html file, I have the following code snippet: <div *ngFor="let r of roles" class="checkb ...

What can be done to prevent the angular material select from overflowing the screen?

I have integrated an Angular Material Select component into my application, which can be found here: https://material.angular.io/components/select/overview. The issue I am facing is that when the select element is positioned near the bottom of the screen a ...

Enhanced capabilities for the <input> element

I am seeking to develop a component that incorporates an <input> tag and offers additional functionalities like a clear text value "X" icon or any other customized actions and markup, all while maintaining the same event bindings ((click), (keyup), e ...

Using lambda expressions in Angular to streamline complex iteration processes

Is there an easy way to shorten this code block: this.markersDisplay = this.markersSource; // Filter Marker Type if (this.isValid(this.selectedMarkersType)) { let markers: Array<Marker> = new Array<Marker>(); for (let ma ...

React 16 exhibiting unexpected behavior with class names

I am trying to implement the classnames object into my input field within a react 16 project, completely independent of the webpack tool. const fieldClassName = classnames( formControlStyles.field, 'form-control' ) The 'form-control& ...

How can you transfer array elements to a new array using JavaScript?

I have a task to transform the fields of an array received from one server so that they can be understood by another server for upload. My approach involves first retrieving and displaying the original field names from the initial server's array to al ...

Updating the view of an HTML page in Angular after a set period of time can be achieved by

I am facing an issue while trying to dynamically display a router link based on a certain condition. The goal is to show the routerLink name within the div section if a specific condition is met. Initially, when I check {{isNameAvailable}}, it returns fals ...

To form a new array object, merge two separate arrays into one

https://stackblitz.com/edit/angular-enctgg-dvagm3 Issue: Attempting to update the hours from arr2 to arr1 and create the desired output below. Trying to achieve this using map function, but unsure how to navigate through nested arrays. Note: Array1 contai ...

Choose a specific location on a vehicle illustration within a pop-up window. The image should be partitioned into 6 separate sections

I have a project for my client where they need to choose a car and then indicate where the damage is located on an image, which is divided into 6 sections. I'm struggling to figure out how to achieve this. I initially thought z-index would work, but ...

Resolving redundancy in Typescript Material-UI Table codebases

Apologies for the ambiguous question title, it was difficult to come up with something more specific. I am currently exploring the Typescript implementation of Material-UI tables, specifically focusing on the table section titled "Sorting and selecting". ...

Having trouble with the Ng multiselect dropdown displaying empty options?

I'm currently facing a challenge in adding a multiselect dropdown feature to my project. Below is the code I have been working on: HTML <ng-multiselect-dropdown [settings]="searchSettings" [data]="dummyList" multiple> </n ...

Error message: TypeScript indicates that the specified column in the postgres database does not exist

Using pg library with TypeScript for querying Postgres, I have constructed a db class as follows: import { Pool } from 'pg'; const pool = new Pool({ host: process.env.PG_HOST, port: parseInt(process.env.PG_PORT), user: process.env.PG ...

Having trouble with image loading in NextJS after replacing an old image with a new one?

I have been attempting to swap out my current banner with different images to test if they work, but every image I try leads to an error when using next/image or even a simple <image> tag. The error message states that "The requested resource isn&apo ...

TypeORM is failing to create a table upon initialization

Recently, I delved into the realm of typescript and decided to explore TypeORM for backend development. My current project involves building a CRUD API using typeORM and postgreSQL. After configuring everything initially, I ran the application only to rea ...

Issue with firing Facebook pixel after router.push() in Next.js

Within this code block is FB pixel tracking code <Script id="some-id" strategy="afterInteractive">some fb pixel code</Script> The issue arises when navigating to a page containing the script using router.push(SOME_ROUTE). T ...