Solve "An error was thrown in afterAll with is not iterable" in Angular test with Karma/Jasmine

Viewed 2090

I'm getting this error with Angular testing running Karma:

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

This is my service that I want to test:

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

My get return an Object like that (DataResponseModel):

{
    data: [{...}]
}

But I need to map it in an object like that

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

This is my test where I have added verify and resetTestingModule after googling hoping to solve the issue but it's seems not working:

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 be have a call /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);
  });

});
1 Answers

It's the first time I am seeing resetTestingModule, I am not sure it is needed.

I think your response is a bit off.

Try this:

  it('should be have a call /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);
  });
Related