once more I'm trying to write a test for a http get request and it fails because of datatyping (at least that's what I suspect).
The request I want to test works and looks like that
getTypeFilter(): Observable<Typefilter[]> {
const url = this.endpoint.getEndpoint() + 'testdata/types?language=' + this.language;
return new Observable<Typefilter[]>(observer => {
this.httpc.get<any[]>(url).subscribe(
(data) => {
const resultData: Typefilter[] = [];
for (const item of data) {
resultData.push(new Typefilter(item.id, item.name));
}
observer.next(resultData);
observer.complete();
},
);
});
}
excerpts from my test file look like this
import { TestBed } from '@angular/core/testing';
import { DataService } from './data.service';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { UrlService } from 'src/app/_services/url.service';
import { Typefilter } from '../_classes/typefilter';
describe('DataService', () => {
let httpMock: HttpTestingController;
let service: DataService;
let urlService: UrlService;
let mockType: Typefilter;
mockType = {id: 1, name: 'News'};
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule]
});
httpMock = TestBed.inject(HttpTestingController);
service = TestBed.inject(DataService);
urlService = TestBed.inject(UrlService);
urlService.getEndpoint = () => ('http://someaddress/');
});
it('getTypeFilter - should return TypeFilter', () => {
service.getTypeFilter().subscribe((data) => {
expect(data).toEqual([mockType]);
});
const reqMock = httpMock.expectOne((req) => req.method === 'GET' && req.url === urlService.getEndpoint() + 'testdata/types?language=' + 'de');
expect(reqMock.request.method).toBe('GET');
reqMock.flush(mockType);
});
});
But it fails with 'TypeError: msgtypefilterkriterium is not iterable' - which I do understand since the data I'm recieving in my request is an array of objects and my mocked Data is only an object. But when I mock this data as an array I do get the error: 'Expected $[0] to be a kind of Object, but was Typefilter({ id: 1, name: 'News' }).' Can anyone help me out how to solve this?
mockType
is an object, whereas getTypeFilter
iterates the response for (const item of data)
. Therefore reqMock.flush
should use an array too.
Try reqMock.flush([mockType]);
about types issues, it could be fixed like that:
service.getTypeFilter().subscribe((data) => {
expect(data).toEqual([new Typefilter(mockType.id, mockType.name)]);
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments