I've been working on writing unit tests for my service that deals with making Http requests.
The service I have returns a Http.get()
request followed by a .map()
function. However, I'm facing issues with getting my mocked backend to respond in a way that doesn't cause an error with the .map()
function. The specific error message I'm encountering is:
this._http.get(...).map is not a function
This article has been my primary reference for this process.
If I remove the .map()
from the service function, the errors disappear. How can I make sure that my mocked response includes a .map()
function that I can utilize?
Please note: I am currently using RC.4
Below is the code snippet for my service:
// Service imports and setup omitted for brevity
@Injectable()
export class BrandDataService {
// Property declarations
constructor (
private _http : Http
) {}
/**
* Get all brands
*/
public getAllBrands () :Observable<any> {
let url = AppSettings.BRAND_API_URL + 'brands';
return this._http.get( url )
.map( this.createAndCacheBrands )
.catch( (error) => {
return Observable.throw( error );
});
}
private createAndCacheBrands (res:Response) {
// Method implementation details
}
}
And here is the spec file where I am utilizing MockBackend
along with other libraries to mock the backend for testing purposes:
// Vendor dependencies and imports omitted for brevity
describe( 'Brand data service', () => {
let service : BrandDataService = null;
let backend : MockBackend = null;
beforeEach(() => {
addProviders([
MockBackend,
BaseRequestOptions,
{
provide : Http,
useFactory : (backendInstance : MockBackend, defaultOptions : BaseRequestOptions) => {
return new Http(backendInstance, defaultOptions);
},
deps : [MockBackend, BaseRequestOptions]
},
BrandDataService
])
})
beforeEach (inject([BrandDataService, MockBackend], (_service : BrandDataService, mockBackend : MockBackend) => {
service = _service;
backend = mockBackend;
}));
it ('should return all brands as an Observable<Response> when requested', (done) => {
// Set the mock backend response options:
backend.connections.subscribe((connection : MockConnection) => {
expect(connection.request.method).toEqual(RequestMethod.Get);
let options = new ResponseOptions({
body : JSON.stringify({
success : true
})
});
connection.mockRespond(new Response(options));
});
// Run the test.
service
.getAllBrands()
.subscribe(
(data) => {
expect(data).toBeDefined();
done();
}
)
});
});