Looking for assistance with unit testing a service I have. The service includes a current json array object that is functioning properly when the observable is subscribed to.
However, I seem to be encountering issues with my unit test setup. Can anyone provide guidance on what I might be doing wrong?
Service Code
getTrackerData(): (Observable<any>) {
return Observable.of(tracker)
.do(data => console.log('trackerdata', data))
.catch(this.handleError)
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
}
DATA
const tracker =
[{
"tracker": "2278474849", "task": 1, "agent": 1, "session": "2278474849-1-1"
}
]
Unit Test
/// <reference path="../../../../node_modules/@types/jasmine/index.d.ts" />
import { TestBed, fakeAsync, inject, tick, async, ComponentFixture, ComponentFixtureAutoDetect } from '@angular/core/testing';
import { MockBackend } from '@angular/http/testing'
import { Http, BaseRequestOptions, Response, ResponseOptions } from '@angular/http'
import { BrowserModule, By } from "@angular/platform-browser";
import { ReactiveFormsModule } from '@angular/forms';
import { Observable } from 'rxjs/Rx'
import { TrackerService } from './tracker.service'
describe('tracker service', () => {
let mockResponse, matchingItem, connection
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
TrackerService,
MockBackend,
BaseRequestOptions,
{
provide: Http,
useFactory: (backend, defaultOptions) => new Http(backend, defaultOptions),
deps: [MockBackend, BaseRequestOptions]
},
]
});
const items =
[{
"tracker": "2278474849", "task": 1, "agent": 1, "session": "2278474849-1-1"
}
];
mockResponse = new Response(new ResponseOptions({ body: items, status: 200 }));
}));
describe('getTrackerData', () => {
//subscribe to connection and storing it later
it('should return all items', inject([TrackerService, MockBackend], (service: TrackerService, backend: MockBackend) => {
backend.connections.subscribe(connection => {
connection.mockRespond(mockResponse);
});
service.getTrackerData() //{ "tracker": "2278474849", "task": 1, "agent": 1, "session": "2278474849-1-1" }
.subscribe((items: any => {
expect(this).toBe(2);
}));
})
});
Experiencing difficulties in the describe
section, as I am fairly new to writing javascript/angular unit tests and have been mixing different examples from my project and online resources which has led to confusion.
It seems like the solution should be straightforward, but the abundance of dependencies I imported has made the process more complex than necessary. Any suggestions on what steps I should take?