In Angular 10 app I am using APP_INITIALIZER to load config file data from config.json file which is inside assets folder in the app. I am using a config service to get the value in this config file.
app.module.ts file
@NgModule({
declarations: [AppComponent],
imports: [CommonModule, BrowserModule, AppRoutingModule, HttpClientModule],
providers: [
{
provide: APP_INITIALIZER,
multi: true,
deps: [ConfigService],
useFactory: (configService: ConfigService) => {
return () => {
return configService.loadConfig();
};
}
}
],
bootstrap: [AppComponent]
})
export class AppModule {}
config.service.ts
@Injectable({
providedIn: 'root'
})
export class ConfigService {
private appConfig: any;
error: any
constructor(private http: HttpClient) { }
loadConfig() {
return this.http.get('assets/config.json')
.toPromise()
.then(data => {
this.appConfig = data;
});
}
get apiBaseUrl() {
if (!this.appConfig) {
throw Error('Config file not loaded!');
}
return this.appConfig.apiBaseUrl;
}
}
When I run the unit test for one of the services which uses the above config service to get the config data, the test fails because the data from config file is not loaded. I used the workaround mentioned in the link Angular APP_INITIALIZER to load config file in tests as shown below but still the config file is not loaded.
The beforeEach block in my test file product-list.service.spec.ts is
beforeEach(async () => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [ProductListService]
});
await TestBed.inject(ApplicationInitStatus).donePromise; // <= Workaround fix which doesn't work
httpTestingController = TestBed.inject(HttpTestingController);
productListService= TestBed.inject(ProductListService);
});
I don't know if I am missing something or doing something the wrong way. Please help me with this issue.