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);
});
});