I am currently in the process of testing a component that relies on a service for making asynchronous HTTP calls. The service returns an Observable, which is then subscribed to by the component.
Snippet from the service code:
getRecentMachineTemperatures(_machine_Id): Observable<IDeviceReadings[]> {
return this.http.get(TemperatureService.URL + _machine_Id)
.map(response => { return response.json(); })
.map((records: Array<any>) => {
let result = new Array<IDeviceReadings>();
if (records) {
records.forEach((record) => {
let device = new IDeviceReadings();
device.device_id = record.device_id;
if (record.d) {
record.d.forEach((t) => {
let temperature = new ITemperature();
temperature.timestamp = t.timestamp;
temperature.value = t.temperature;
device.temperatures.push(temperature);
});
}
result.push(device);
});
}
return result;
});
}
Snippet from the component code:
ngOnInit() {
this.getRecentTemperatures();
}
getRecentTemperatures() {
this.temperatureService.getRecentMachineTemperatures(this.machine_id)
.subscribe(
res => {
let device1 = res[0];
this.deviceId = device1.device_id;
this.initTemperatures(device1.temperatures);
this.updateChart();
},
error => console.log(error));
}
During my testing process, I set up dependencies and spy on the 'getRecentMachineTemperatures' service method. However, despite multiple attempts at writing tests, each resulted in a different error.
In my test file 'temperature.component.spec.ts', here's my setup:
let machine_id = 1;
let comp: TemperatureComponent;
let fixture: ComponentFixture<TemperatureComponent>;
let de: DebugElement;
let el: HTMLElement;
let temperatureService: TemperatureService;
let stubDevices: IDeviceReadings[];
let stubTemperatures: ITemperature[];
let spyRecentTemps: Function;
describe('Component: Temperature', () => {
// Test setup code goes here
});
The tests using fakeAsync, async, and async (done) are producing various errors including timer queue issues and problems with setInterval within an async zone test.
Any suggestions on how to effectively test components with async service dependencies? Has there been any progress made in fixing these issues or are there workarounds available?
For reference, I am working with angular-cli version 1.0.0-beta.16, node version 4.4.2, npm version 3.10.6, and webpack version 2.1.0-beta.22.