I am struggling with writing a unit test for a function that indirectly triggers multiple HTTP requests.
The service I am testing has the following structure:
/* content.service.ts */
import { Injectable } from "@angular/core"
import { ApiService } from "services/api/api.service"
@Injectable()
export class ContentService {
public languages: Array<any>
public categories: Array<any>;
constructor(private apiService: ApiService) {}
public async fetchLanguages(): Promise<boolean> {
const data: any = await this.apiService.getData("language");
if (!data) return false;
this.languages = data;
return true;
}
public async fetchCategories(): Promise<boolean> {
const data: any = await this.apiService.getData("category");
if (!data) return false;
this.categories = data;
return true;
}
public async initService(): Promise<boolean> {
const statusLanguages: boolean = await this.fetchLanguages();
if (!statusLanguages) return false;
const statusCategories: boolean = await this.fetchCategories();
if (!statusCategories) return false;
return true;
}
}
The test file for the service is structured as follows:
/* content.service.spec.ts */
import {
HttpClientTestingModule,
HttpTestingController
} from "@angular/common/http/testing"
import { TestBed } from "@angular/core/testing"
import { ApiService } from "services/api/api.service"
import { ContentService } from "./content.service"
describe("ContentService:", () => {
let contentService: ContentService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule ],
providers: [ ApiService, ContentService ]
});
contentService = TestBed.get(ContentService);
httpMock = TestBed.get(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
/* Dummy data */
const languages = [
{ id: 1, uid: "en", active: true },
{ id: 2, uid: "es", active: false },
{ id: 3, uid: "hr", active: false }
];
const categories = [
{ id: 1, uid: "default" },
{ id: 2, uid: "alternative" }
];
describe("initService:", () => {
it("successful response", (done: DoneFn) => {
contentService.initService().then(result => {
expect(result).toEqual(true);
expect(contentService.languages).toEqual(languages);
expect(contentService.categories).toEqual(categories);
done();
});
const requests = httpMock.match(req => !!req.url.match(/api\/data/));
expect(requests.length).toBe(2);
requests[0].flush({ status: "ok", data: languages });
requests[1].flush({ status: "ok", data: categories });
});
});
});
While running unit tests with ng test
, an error is encountered:
TypeError: Cannot read property 'flush' of undefined
This TypeError specifically points to the line:
requests[1].flush({ status: "ok", data: categories })
From this, it appears that the first request is handled correctly, but not the second one.
Shouldn't the match
method from the HttpTestingController capture all matching HTTP requests based on the provided regular expression?