I am facing an issue with a service that returns a Promise. It retrieves data from a JSON file using a subscribe method before resolving the Promise.
I am trying to test the result of this Promise based on the parameters I provide, but I am encountering two problems. Either the test times out with an error message saying "Exceeded timeout of 5000 ms for a test," or the test passes incorrectly because the subscribe part is not being executed.
service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
export interface IAppConfig {
env: {
name: string;
};
features: {
[key: string]: boolean;
};
}
@Injectable({
providedIn: 'root',
})
export class ConfigService {
static appSettings: IAppConfig;
constructor(private http: HttpClient) {}
load() {
const jsonFile = displayJsonFile
? `../../../../assets/.json1`
: `../../../../assets/.json2`;
return new Promise<any>((resolve) =>
this.http.get(jsonFile).subscribe((res) => {
appSettings = res
resolve(res);
})
);
}
}
import { TestBed, tick } from '@angular/core/testing';
import { ConfigService } from './config-service.service';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HttpClient } from '@angular/common/http';
describe('ConfigService', () => {
let service: AppConfigService;
let httpMock: HttpTestingController;
const mockConfig = {
env: {
name: 'json1',
},
features: {
feature1: true,
feature2: true,
},
};
beforeEach(() => {
TestBed.configureTestingModule({ imports: [HttpClientTestingModule] });
service = TestBed.inject(AppConfigService);
httpMock = TestBed.inject(HttpTestingController);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should load config file when environment is prod', () => {
service.load().then(res => expect(res).toBe(mockConfig)
});
});