I am facing an issue with a component that relies on a service to fetch data. The service also retrieves configurations from a static variable in the Configuration Service, but during Karma tests, the const variable is showing up as undefined.
Although I know I can create a mock service, I am unsure whether creating 2 services to test this component is the right approach. Additionally, if I do need to create mock services for other components that use the Configuration Service, it seems like a lot of extra work without a clear solution :( I have included both the ConfigurationService and the Service being used, in case that helps.
TypeError: Cannot read property 'apiUrl' of undefined
The apiUrl property is part of the conf static variable in the ConfigurationService.
ConfigService.ts
import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import * as YAML from 'js-yaml';
import {Config} from './models/Config';
@Injectable()
export class ConfigService {
public static conf: Config;
constructor(private http: HttpClient) {}
async load() {
const res = await this.http.get<Config>('assets/config.yml', {responseType: 'text' as 'json'}).toPromise();
ConfigService.conf = YAML.load(res).environment;
}
}
InfoService.ts
export class InfoService {
private InfoUrl = ConfigService.conf.apiUrl + '/info';
constructor(private http: HttpClient) {}
getInfo(){
return http.get(InfoUrl);
}
}
InfoComponent.ts
export class InfoComponent implements OnInit {
private info;
constructor(private infoService: InfoService) {}
ngOnInit() {}
loadInfo() {
this.info = this.infoService.getInfo();
}
InfoComponent.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { InfoComponent } from './info.component';
import {HttpClientModule} from '@angular/common/http';
import {InfoService} from './info.service';
import {ConfigService} from '../shared/config.service';
describe('InfoComponent', () => {
let component: InfoComponent;
let fixture: ComponentFixture<InfoComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpClientModule],
declarations: [InfoComponent],
providers: [
ConfigService
InfoService,
],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(InfoComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});