I am trying to write unit tests for my API service but have some trouble catching HTTP errors. I am following this guide along with the Angular2 docs since the guide is (slightly) out of date in some minor areas.
All unit tests pass apart from those where an error is thrown by the service (due to error HTTP status code). I can tell this by logging out response.ok. From what i've read this has something to do with the unit tests not executing asynchronously, hence, not waiting for the error response. However, I have no idea why this is the case here since I have used the async() utility function in the beforeEach method.
API Service
get(endpoint: string, authenticated: boolean = false): Observable<any> {
endpoint = this.formatEndpoint(endpoint);
return this.getHttp(authenticated) // Returns #angular/http or a wrapper for handling auth headers
.get(endpoint)
.map(res => this.extractData(res))
.catch(err => this.handleError(err)); // Not in guide but should work as per docs
}
private extractData(res: Response): any {
let body: any = res.json();
return body || { };
}
private handleError(error: Response | any): Observable<any> {
// TODO: Use a remote logging infrastructure
// TODO: User error notifications
let errMsg: string;
if (error instanceof Response) {
const body: any = error.json() || '';
const err: string = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''}${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
Error unit test
// Imports
describe('Service: APIService', () => {
let backend: MockBackend;
let service: APIService;
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
BaseRequestOptions,
MockBackend,
APIService,
{
deps: [
MockBackend,
BaseRequestOptions
],
provide: Http,
useFactory: (backend: XHRBackend, defaultOptions: BaseRequestOptions) => {
return new Http(backend, defaultOptions);
}
},
{provide: AuthHttp,
useFactory: (http: Http, options: BaseRequestOptions) => {
return new AuthHttp(new AuthConfig({}), http, options);
},
deps: [Http, BaseRequestOptions]
}
]
});
const testbed: any = getTestBed();
backend = testbed.get(MockBackend);
service = testbed.get(APIService);
}));
/**
* Utility function to setup the mock connection with the required options
* #param backend
* #param options
*/
function setupConnections(backend: MockBackend, options: any): any {
backend.connections.subscribe((connection: MockConnection) => {
const responseOptions: any = new ResponseOptions(options);
const response: any = new Response(responseOptions);
console.log(response.ok); // Will return false during the error unit test and true in others (if spyOn log is commented).
connection.mockRespond(response);
});
}
it('should log an error to the console on error', () => {
setupConnections(backend, {
body: { error: `Some strange error` },
status: 400
});
spyOn(console, 'error');
spyOn(console, 'log');
service.get('/bad').subscribe(null, e => {
// None of this code block is executed.
expect(console.error).toHaveBeenCalledWith("400 - Some strange error");
console.log("Make sure an error has been thrown");
});
expect(console.log).toHaveBeenCalledWith("Make sure an error has been thrown."); // Fails
});
Update 1
when I check the first callback, response.ok is undefined. This leads me to believe that there is something wrong in the setupConnections utility.
it('should log an error to the console on error', async(() => {
setupConnections(backend, {
body: { error: `Some strange error` },
status: 400
});
spyOn(console, 'error');
//spyOn(console, 'log');
service.get('/bad').subscribe(res => {
console.log(res); // Object{error: 'Some strange error'}
console.log(res.ok); // undefined
}, e => {
expect(console.error).toHaveBeenCalledWith("400 - Some strange error");
console.log("Make sure an error has been thrown");
});
expect(console.log).toHaveBeenCalledWith("Make sure an error has been thrown.");
}));
Update 2
If, instead of catching errors in the get method I do it explicitly in map then still have same problem.
get(endpoint: string, authenticated: boolean = false): Observable<any> {
endpoint = this.formatEndpoint(endpoint);
return this.getHttp(authenticated).get(endpoint)
.map(res => {
if (res.ok) return this.extractData(res);
return this.handleError(res);
})
.catch(this.handleError);
}
Update 3
After some discussion this issue submitted
Here is my working solution which is similar to above suggestions but with more clarity:
it('should log an error to the console on error', async(inject([AjaxService, MockBackend], (
ajaxService: AjaxService, mockBackend: MockBackend) => {
service = ajaxService;
backend = mockBackend;
backend.connections.subscribe((connection: MockConnection) => {
const options: any = new ResponseOptions({
body: { error: 'Some strange error' },
status: 404
});
const response: any = new Response(options);
connection.mockError(response);
});
spyOn(console, 'error');
service.get('/bad').subscribe(res => {
console.log(res); // Object{error: 'Some strange error'}
}, e => {
expect(console.error).toHaveBeenCalledWith('404 - Some strange error');
});
})));
Reference full working code:
Below are all possible test scenarios.
Note: Don't worry about AjaxService. It's my custom wrapper on angular http service which is being used as a interceptor.
ajax.service.spec.ts
import { AjaxService } from 'app/shared/ajax.service';
import { TestBed, inject, async } from '#angular/core/testing';
import { Http, BaseRequestOptions, ResponseOptions, Response } from '#angular/http';
import { MockBackend, MockConnection } from '#angular/http/testing';
describe('AjaxService', () => {
let service: AjaxService = null;
let backend: MockBackend = null;
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
MockBackend,
BaseRequestOptions,
{
provide: Http,
useFactory: (backendInstance: MockBackend, defaultOptions: BaseRequestOptions) => {
return new Http(backendInstance, defaultOptions);
},
deps: [MockBackend, BaseRequestOptions]
},
AjaxService
]
});
}));
it('should return mocked post data',
async(inject([AjaxService, MockBackend], (
ajaxService: AjaxService, mockBackend: MockBackend) => {
service = ajaxService;
backend = mockBackend;
backend.connections.subscribe((connection: MockConnection) => {
const options = new ResponseOptions({
body: JSON.stringify({ data: 1 }),
});
connection.mockRespond(new Response(options));
});
const reqOptions = new BaseRequestOptions();
reqOptions.headers.append('Content-Type', 'application/json');
service.post('', '', reqOptions)
.subscribe(r => {
const out: any = r;
expect(out).toBe(1);
});
})));
it('should log an error to the console on error', async(inject([AjaxService, MockBackend], (
ajaxService: AjaxService, mockBackend: MockBackend) => {
service = ajaxService;
backend = mockBackend;
backend.connections.subscribe((connection: MockConnection) => {
const options: any = new ResponseOptions({
body: { error: 'Some strange error' },
status: 404
});
const response: any = new Response(options);
connection.mockError(response);
});
spyOn(console, 'error');
service.get('/bad').subscribe(res => {
console.log(res); // Object{error: 'Some strange error'}
}, e => {
expect(console.error).toHaveBeenCalledWith('404 - Some strange error');
});
})));
it('should extract mocked data with null response',
async(inject([AjaxService, MockBackend], (
ajaxService: AjaxService, mockBackend: MockBackend) => {
service = ajaxService;
backend = mockBackend;
backend.connections.subscribe((connection: MockConnection) => {
const options = new ResponseOptions({
});
connection.mockRespond(new Response(options));
});
const reqOptions = new BaseRequestOptions();
reqOptions.headers.append('Content-Type', 'application/json');
service.get('test', reqOptions)
.subscribe(r => {
const out: any = r;
expect(out).toBeNull('extractData method failed');
});
})));
it('should log an error to the console with empty response', async(inject([AjaxService, MockBackend], (
ajaxService: AjaxService, mockBackend: MockBackend) => {
service = ajaxService;
backend = mockBackend;
backend.connections.subscribe((connection: MockConnection) => {
const options: any = new ResponseOptions({
body: {},
status: 404
});
const response: any = new Response(options);
connection.mockError(response);
});
spyOn(console, 'error');
service.get('/bad').subscribe(res => {
console.log(res); // Object{error: 'Some strange error'}
}, e => {
expect(console.error).toHaveBeenCalledWith('404 - {}');
});
// handle null response in error
backend.connections.subscribe((connection: MockConnection) => {
connection.mockError();
});
const res: any = null;
service.get('/bad').subscribe(res, e => {
console.log(res);
}, () => {
expect(console.error).toHaveBeenCalledWith(null, 'handleError method with null error response got failed');
});
})));
});
ajax.service.ts
import { Injectable } from '#angular/core';
import { Http, Response, RequestOptionsArgs, BaseRequestOptions } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';
/**
* Wrapper around http, use this for all http operations.
* It has centralized error handling as well.
* #export
* #class AjaxService
*/
#Injectable()
export class AjaxService {
/**
* Creates an instance of AjaxService.
* #param {Http} http
*
* #memberOf AjaxService
*/
constructor(
private http: Http,
) { }
/**
* Performs a request with get http method.
*
* #param {string} url
* #param {RequestOptionsArgs} [options]
* #returns {Observable<Response>}
*
* #memberOf AjaxService
*/
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
options = this.getBaseRequestOptions(options);
options = this.setHeaders(options);
return this.http.get(url, options)
.map(this.extractData)
.catch(this.handleError);
}
/**
* Performs a request with post http method.
*
* #param {string} url
* #param {*} body
* #param {RequestOptionsArgs} [options]
* #returns {Observable<Response>}
*
* #memberOf AjaxService
*/
post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
options = this.getBaseRequestOptions(options);
options = this.setHeaders(options);
return this.http.post(url, body, options)
.map(this.extractData)
.catch(this.handleError);
}
/**
* Util function to fetch data from ajax response
*
* #param {Response} res
* #returns
*
* #memberOf AjaxService
*/
private extractData(res: Response) {
const body = res.json();
const out = body && body.hasOwnProperty('data') ? body.data : body;
return out;
}
/**
* Error handler
* Future Scope: Put into remote logging infra like into GCP stackdriver logger
* #param {(Response | any)} error
* #returns
*
* #memberOf AjaxService
*/
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''}${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
/**
* Init for RequestOptionsArgs
*
* #private
* #param {RequestOptionsArgs} [options]
* #returns
*
* #memberOf AjaxService
*/
private getBaseRequestOptions(options: RequestOptionsArgs = new BaseRequestOptions()) {
return options;
}
/**
* Set the default header
*
* #private
* #param {RequestOptionsArgs} options
* #returns
*
* #memberOf AjaxService
*/
private setHeaders(options: RequestOptionsArgs) {
if (!options.headers || !options.headers.has('Content-Type')) {
options.headers.append('Content-Type', 'application/json');
}
return options;
}
}
From what i've read this has something to do with the unit tests not executing asynchronously, hence, not waiting for the error response. However, I have no idea why this is the case here since I have used the async() utility function in the beforeEach method
You need to use it in the test case (the it). What async does is create an test zone that waits for all async tasks to complete before completing the test (or test area, e.g. beforeEach).
So the async in the beforeEach is only waiting for the async tasks to complete in the method before exiting it. But the it also needs that same thing.
it('should log an error to the console on error', async(() => {
}))
UPDATE
Aside from the missing async, there seems to be a bug with the MockConnection. If you look at the mockRespond, it always calls next, not taking into consideration the status code
mockRespond(res: Response) {
if (this.readyState === ReadyState.Done || this.readyState === ReadyState.Cancelled) {
throw new Error('Connection has already been resolved');
}
this.readyState = ReadyState.Done;
this.response.next(res);
this.response.complete();
}
They have a mockError(Error) method, which is what calls error
mockError(err?: Error) {
// Matches ResourceLoader semantics
this.readyState = ReadyState.Done;
this.response.error(err);
}
but this does not call allow you to pass a Response. This is inconsistent with how the real XHRConnection works, which checks for the status, and sends the Response either through the next or error, but is the same Response
response.ok = isSuccess(status);
if (response.ok) {
responseObserver.next(response);
// TODO(gdi2290): defer complete if array buffer until done
responseObserver.complete();
return;
}
responseObserver.error(response);
Sounds like a bug to me. Something you should probably report. They should allow you to either send the Response in the mockError or do the same check in the mockRespond that they do in the XHRConnection.
Updated (by OP) SetupConnections()
Current solution
function setupConnections(backend: MockBackend, options: any): any {
backend.connections.subscribe((connection: MockConnection) => {
const responseOptions: any = new ResponseOptions(options);
const response: any = new Response(responseOptions);
// Have to check the response status here and return the appropriate mock
// See issue: https://github.com/angular/angular/issues/13690
if (responseOptions.status >= 200 && responseOptions.status <= 299)
connection.mockRespond(response);
else
connection.mockError(response);
});
}
Related
I want to write a unit test for my payment service but I'm receiving this error:
source.subscribe is not a function
at ./node_modules/rxjs/src/internal/lastValueFrom.ts:60:12
This is my service
import { HttpService } from '#nestjs/axios';
import { Injectable } from '#nestjs/common';
import { lastValueFrom } from 'rxjs';
import { PaymentInfo } from 'src/utils/types/paymentInfo';
#Injectable()
export class PaymentsService {
constructor(private readonly httpService: HttpService) {}
private createHeaderWithAuth(auth, contentType = 'application/json') {
return {
headers: {
authorization: auth.replace('Bearer', '').trim(),
'Content-Type': contentType,
},
};
}
async makePayment(auth: string, paymentInfo: PaymentInfo) {
const configs = this.createHeaderWithAuth(auth);
const response = await lastValueFrom(
await this.httpService.post(
`${process.env.PAYMENT_URL}/transaction/pay`,
paymentInfo,
configs
)
).catch((error) => {
console.log(error);
throw new Error(error.response.data.message);
});
return response.data;
}
}
So with a bit of searching and tinkering found out that this is caused by my import of a rxjs function to resolve the observable setted by axios.
I've searched ways to mock this function so I can properly test my service. But none of them gave me a solution, the questions i found only revolved around functions with modules, but these have none since is imported from a third party lib.
This is my test suite:
describe('Payments Service', () => {
let service: PaymentsService;
let mockedHttpService = {
post: jest
.fn()
.mockImplementation(
async (
url: string,
paymentInfo: PaymentInfo,
header = mockedHeader
) => {
return { mockedSuccessfulResponse };
}
),
get: jest
.fn()
.mockImplementation(async (url: string, header = mockedHeader) => {
return { ...mockedSuccessfulResponse, data: mockedUserCards };
}),
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
PaymentsService,
{
provide: HttpService,
useValue: mockedHttpService,
},
],
}).compile();
service = module.get<PaymentsService>(PaymentsService);
});
describe('Initialize', () => {
it('should define service', () => {
expect(service).toBeDefined();
});
describe('makePayment', () => {
it('should make a payment', async () => {
const payment = await service.makePayment(mockedAuth, mockedPaymentInfo);
expect(mockedHttpService.post).toHaveBeenCalledWith(
`${process.env.PAYMENT_URL}/transaction/pay`,
mockedPaymentInfo,
mockedHeader
);
expect(payment).toBe(mockedSuccessfulResponse);
});
});
});
Ps.: I removed the mocked objects to reduce the amount of code to read
you should use the of operator from rxjs, and drop the async keyword. Like:
.mockImplementation(
(
url: string,
paymentInfo: PaymentInfo,
header = mockedHeader
) => {
return of({ mockedSuccessfulResponse });
}
otherwise lastValueFrom won't receive an observable object.
I am trying to create async tests with axios-mock and jest.
This is my test file:
var axios = require('axios');
var MockAdapter = require('axios-mock-adapter');
const middlewares = [thunk,axiosMiddleware]
const mockStore = configureMockStore(middlewares)
describe('async-actions', () => {
var instance;
var mock;
beforeEach(function() {
instance = axios.create();
mock = new MockAdapter(instance);
});
afterEach(() => {
mock.reset()
mock.restore()
})
it('creates FETCH_BOOKINGS_SUCCESS when fetch bookings has been done', () => {
mock
.onGet('/bookings').reply(200, {
data: [
{ id: 1, name: 'test booking' }
]
});
const expectedActions = [
{type: "FETCH_BOOKINGS_START" },
{type: "FETCH_BOOKINGS_SUCCESS", }
]
const store = mockStore({
session: {
token: {
token: "test_token"
}
}
})
return store.dispatch(actions.fetchBookingsTest())
.then(
() => {
expect(store.getActions()).toEqual(expectedActions)
})
// return of async actions
})
})
And my action:
export function fetchBookingsTest() {
return (dispatch) => {
dispatch(async.fetchDataStart(namedType));
return dispatch(rest.get(BOOKINGS))
.then(
(data) => {
dispatch(async.fetchDataSuccess(data,namedType));
},
(error) => {
dispatch(async.fetchDataFailure(error,namedType));
}
)
}
}
I have middleware setup that uses the authentication token from the redux store for each get request. That is why I have setup "test_token" in the mock store.
When I run this test I receive the response
[{"type": "FETCH_BOOKINGS_START"}, {"payload": [Error: Network Error], "type": "FETCH_BOOKINGS_FAILURE"}]
Why am I getting a network error? Do i need to do more setup with Jest to avoid authentication with mock-axios?
I have a DataService and I want to assert that the year is getting set in the query string correctly. Is there a way to spyOn the http.get call or to access it? I don't know the correct approach to testing this. I'm using Angular 2.2.0.
The DataService
constructor(private http: Http) { }
public getEnergyData(option: string): Promise<EnergyDataDto[]> {
return this.http.get(this.getEnergyDataApiUrl(option)).toPromise().then((response) => {
this.energyDataCache = this.parseEnergyDataResponse(response);
return this.energyDataCache;
}).catch(this.handleError);
}
protected getEnergyDataApiUrl(option: string) {
return `/api/solar?year=${option}`;
}
protected parseEnergyDataResponse(response: Response) {
return response.json().data;
}
dataservice.spec.ts
describe('Given the DataService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [DataService, { provide: XHRBackend, useClass: MockBackend }],
});
});
describe('When getting the energy data', () => {
let backend: MockBackend;
let service: EnergyDataService;
let fakeEnergyData: EnergyDataDto[];
let response: Response;
const makeEnergyData = () => {
let data = [];
let one = new EnergyDataDto();
one.year = 2007;
one.countryName = 'Denmark';
one.quantity = '100000';
data.push(one);
return data;
};
beforeEach(inject([Http, XHRBackend], (http: Http, be: MockBackend) => {
backend = be;
service = new EnergyDataService(http);
fakeEnergyData = makeEnergyData();
let options = new ResponseOptions({ status: 200, body: { data: fakeEnergyData } });
response = new Response(options);
}));
it('should return fake values', async(inject([], () => {
backend.connections.subscribe((c: MockConnection) => c.mockRespond(response));
service.getEnergyData('all').then(data => {
expect(data.length).toBe(1);
expect(data[0].countryName).toBe('Denmark');
});
})));
it('should use year in query string', async(inject([], () => {
spyOn(service, 'getEnergyDataApiUrl').and.callThrough();
backend.connections.subscribe((c: MockConnection) => c.mockRespond(response));
service.getEnergyData('2007').then(data => {
// I was hoping to use backendend somehow instead, but it's not in scope when I debug it.
expect((<any>service).getEnergyDataApiUrl).toHaveBeenCalledWith('/api/solar?year=2007');
});
})));
You should do this in the mockBackend.connections subscription. This is when you have access to the URL from the MockConnection
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.url).toBe(...)
c.mockRespond(response)
});
I write test cases in angular 2.I want to know how following thing done. please help me.
How to define Mocking (Http, router) globally.
How to call common beforeEach() in every test cases.
My code which i want to common.
common.ts
/* this used for route Mocking
* */
let mockRouter = {
navigate: jasmine.createSpy('navigate')
}
/*
* Response Url
* */
let metaUrl = {
LOGIN: '/operator/login',
META_API: '/meta-api'
};
let subject:GlobalUtils = null;
let backend:MockBackend = null;
let http:Http = null;
/*
* The beforeEach function is called once before each spec in the describe in which it is called
* */
beforeEach(()=>TestBed.configureTestingModule({
providers: [
GlobalUtils,
BaseRequestOptions,
MockBackend,
{
provide: Router, useValue: mockRouter
},
{
provide: Http,
useFactory: function (backend:ConnectionBackend, defaultOptions:BaseRequestOptions) {
return new Http(backend, defaultOptions);
},
deps: [MockBackend, BaseRequestOptions]
},
]
}));
beforeEach(inject([GlobalUtils, MockBackend, Http], (_globalUtils:GlobalUtils, mockBackend:MockBackend, _http:Http) => {
subject = _globalUtils;
backend = mockBackend;
http = _http;
}));
Reason behind this I exactly this in another spec.ts file for write test case.
here is my spec.ts files
1.spec.ts
import {Http, BaseRequestOptions, Response, ResponseOptions, ConnectionBackend} from '#angular/http';
import {MockBackend, MockConnection} from '#angular/http/testing';
import {Router} from '#angular/router';
import {TestBed, inject} from '#angular/core/testing';
import {GlobalUtils} from '../global.utils.ts';
import { Constant } from '../constant'
describe('Global Utils : Meta urls API', () => {
/* this used for route Mocking
* */
let mockRouter = {
navigate: jasmine.createSpy('navigate')
}
/*
* Response Url
* */
let metaUrl = {
LOGIN: '/operator/login',
META_API: '/meta-api'
};
let subject:GlobalUtils = null;
let backend:MockBackend = null;
let http:Http = null;
/*
* The beforeEach function is called once before each spec in the describe in which it is called
* */
beforeEach(()=>TestBed.configureTestingModule({
providers: [
GlobalUtils,
BaseRequestOptions,
MockBackend,
{
provide: Router, useValue: mockRouter
},
{
provide: Http,
useFactory: function (backend:ConnectionBackend, defaultOptions:BaseRequestOptions) {
return new Http(backend, defaultOptions);
},
deps: [MockBackend, BaseRequestOptions]
},
]
}));
beforeEach(inject([GlobalUtils, MockBackend, Http], (_globalUtils:GlobalUtils, mockBackend:MockBackend, _http:Http) => {
subject = _globalUtils;
backend = mockBackend;
http = _http;
}));
/*
* This Test case is check Response of getMetaUrls function
* getMetaUrls must return response
* */
it('Should have get Meta urls', (done) => {
// HTTP Mocking
backend.connections.subscribe((connection:MockConnection)=> {
let options = new ResponseOptions({
body: JSON.stringify(metaUrl),status: 200
});
connection.mockRespond(new Response(options));
});
/*
* we mock http get method
* */
http
.get(Constant.metaUrl)
.subscribe((response) => {
subject.getMetaUrls();
expect(Constant.saveUrl).toEqual(metaUrl);
done();
});
});
/*
* This Test case is check empty response and redirect to error page
* getMetaUrls must return empty response
* */
it('Should have get Empty Meta urls data', (done) => {
backend.connections.subscribe((connection:MockConnection)=> {
let options = new ResponseOptions({
body: JSON.stringify(''), status: 200
});
connection.mockRespond(new Response(options));
});
http
.get(Constant.metaUrl)
.subscribe((response) => {
subject.getMetaUrls();
expect(mockRouter.navigate).toHaveBeenCalledWith(['page-error']);
done();
});
});
2.spec.ts
describe('Authentication test',()=>{
});
2.spec file blank now because I want to use common.ts function in this file and I want to know how.
I m writing a Uni-test for a login Method with an HTTP.post call, like:
this.http.post( endpoint, creds, { headers: headers})
.map(res => res.json())
.subscribe(
data => this.onLoginComplete(data.access_token, credentials),
err => this.onHttpLoginFailed(err),
() => this.trace.debug(this.componentName, "Login completed.")
);
The problem is that i'm not able to simulate the error branch; everytime is called the onLoginComplete Method;
here is my test:
it("check that Atfer Login, console show an error ", inject(
[TraceService, Http, MockBackend, WsiEndpointService],
(traceService: TraceService, http: Http,
backend: MockBackend, wsiEndpoint: WsiEndpointService) => {
let tokenTest: number = 404 ;
let response: ResponseOptions = null {} // i think i have to modify this
let connection: any;
backend.connections.subscribe((c: any) => connection = c);
let authService: AuthService = new AuthService(http, Service1, Service2);
authenticationservice.login({ "username": "a", "password": "1" });
connection.mockRespond(new Response(response));
expect(ERROR);
}));
Thanks again to everyone.
First you need to override the XHRBackend class by the MockBackend one:
describe('HttpService Tests', () => {
beforeEachProviders(() => {
return [
HTTP_PROVIDERS,
provide(XHRBackend, { useClass: MockBackend }),
HttpService
];
});
(...)
});
Notice that HttpService is the service that uses the Http object and I want to test.
Then you need to inject the mockBackend and subscribe on its connections property. When a request is sent, the corresponding callback is called and you can specify the response elements like the body. The service will receive this response as the response of the call. So you'll be able to test your service method based on this.
Below I describe how to test the getItems method of the HttpService:
it('Should return a list of items', inject([XHRBackend, HttpService, Injector], (mockBackend, httpService, injector) => {
mockBackend.connections.subscribe(
(connection: MockConnection) => {
connection.mockRespond(new Response(
new ResponseOptions({
body: [ { id: '1', label: 'item1' }]
})));
});
httpService.getItems().subscribe(
items => {
expect(items).toEqual([ { id: '1', label: 'item1' }]);
});
});
});
Here is the code of getItems method of the HttpService:
#Injectable()
export class HttpService {
constructor(private http:Http) {
}
getItems(): Observable<any[]> {
return this.http.get('/items').map(res => res.json());
}
}
To simulate an error simply use the mockError method instead of the mockResponseone:
mockBackend.connections.subscribe(
(connection: MockConnection) => {
connection.mockError(new Error('some error'));
});
You can simulate an error like this:
connection.mockError(new Response(new ResponseOptions({
body: '',
status: 404,
})));
I created a small class
import {ResponseOptions, Response} from '#angular/http';
export class MockError extends Response implements Error {
name: any;
message: any;
constructor(status: number, body: string = '') {
super(new ResponseOptions({status, body}));
}
}
which can use like this
connection.mockError(new MockError(404));