I don't know what I'm missing but when I added APP_INITIALIZER to load the API url in my angular application, the tests stopped working because the Auth service can't find the url
test.spec.ts
describe('AppSevice', () => {
let injector: TestBed;
let service: AppService;
let appConfig: AppConfigService;
let httpMock: HttpTestingController;
beforeAll(() => {
console.log('beforeAll');
TestBed.resetTestEnvironment();
TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
});
beforeEach(async () => {
console.log('beforeEach');
TestBed.configureTestingModule({
imports: [ HttpClientTestingModule, RouterTestingModule ],
providers: [ AppConfigService, AppService ]
});
injector = getTestBed();
appConfig = injector.get(AppConfigService);
service = injector.get(AppService);
httpMock = injector.get(HttpTestingController); <---cant read property 'serviceBaseUrl' of undefined
});
...
AppConfigService.ts <--- this is a service load url from JSON
@Injectable({
providedIn: 'root'
})
export class AppConfigService {
private appConfig: any;
constructor(private injector: Injector) {}
async loadAppConfig() {
let http = this.injector.get(HttpClient);
return http
.get('./assets/app-config.json')
.toPromise()
.then((data) => {
this.appConfig = data;
// window['app-config'] = data;
})
.catch((er) => {
console.error('>>>> Problem getting app-config <<<<', er);
this.appConfig = environment;
// window['app-config'] = environment;
});
}
config() {
return this.appConfig;
}
}
app.module.ts <---this is a main module with a APP_INITIALIZER
const appInitializerFn = (appConfig: AppConfigService) => {
return async () => {
return await appConfig.loadAppConfig();
};
};
@NgModule({
declarations: [ ... ],
imports: [
...
],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AppInterceptor,
multi: true
},
AppConfigService,
{
provide: APP_INITIALIZER,
useFactory: appInitializerFn,
multi: true,
deps: [ AppConfigService, Injector ]
}
],
bootstrap: [ AppComponent ]
})
export class AppModule {}
and this is a auth service
auth.service.ts
@Injectable({
providedIn: 'root'
})
export class AuthService {
/**
* Apiurl of auth service
*/
private APIURL: string;
/**
* Http options of auth service
*/
private httpOptions = {
headers: new HttpHeaders({
'Content-type': 'application/x-www-form-urlencoded; charset=utf-8'
// Authorization: 'Basic ...'
})
};
/**
* Creates an instance of auth service.
* @param http
*/
constructor(private http: HttpClient, private appconfig: AppConfigService) {
this.APIURL = appconfig.config().servicesBaseUrl;
}
...
app-config.json
{
"servicesBaseUrl": "http://...."
}
the application works perfect but the tests fail all because they do not recognize the url
Aucun commentaire:
Enregistrer un commentaire