Unni Krishnan D
2 min readApr 9, 2017

AngularJS 2 $http testing with Jasmine

Prerequisites
1.Basic knowledge of AngularJS 2 ,Jasmine
2.Understanding of “What is $http call ” ,basically how an API call works

First lets configure our component

import { Component } from ‘@angular/core’;
import { Http, Response } from ‘@angular/http’;

//including dependencies for catch and map
import ‘rxjs/add/operator/catch’;
import ‘rxjs/add/operator/map’;
@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [‘./app.component.css’]
})
export class AppComponent {
public ajaxdata;
constructor (private http: Http) {
this.ajaxdata = {}; //a simple variable to bind API data to HTML
}


callApi() {
return this.http.get(‘https://jsonplaceholder.typicode.com/posts/1')
.map(res => res.json()); //return as JSON
}

fetchApi() { //function for subscribing the data
this.callApi()
.subscribe(
data => this.handleData(data),
err => this.handleError(err),

);
}

handleData(data){
console.log(data);
this.ajaxdata = data.body; //ajaxdata , variable to hold the API repsonseand binding it o the html

console.log(this.ajaxdata);

}
handleError(data){
console.log(data);
}
}

Lets see out HTML

<button (click)=”fetchApi()”>Call API </button>
<div>Server response</div>
<div id =”titledata”>{{ajaxdata}}</div>

So the functionality is simple and clean on click of the “Call API ” button , we will get the response :)

Testing this $http call using Jasmine

In our appcomponent.spec.ts ,include all the required libraries

import { TestBed, async, inject } from ‘@angular/core/testing’;
import {
HttpModule,
Http,
Response,
ResponseOptions,
XHRBackend
} from ‘@angular/http’;
import { MockBackend } from ‘@angular/http/testing’;

import { AppComponent } from ‘./app.component’;

Now we have to configure our TestBed ,we use MockBackend for testing $http calls

The beforeEach section ,we have to include MockBackend

beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpModule],

declarations: [
AppComponent
],
providers:[
AppComponent,
{ provide: XHRBackend, useClass: MockBackend },
],
}).compileComponents();

}));

Now lets write our test case

it(‘should return a mock API’,
inject([AppComponent, XHRBackend], (app, xhr) => {

const mockResponse = {
body:”body from mock”
};

xhr.connections.subscribe((connection) => {
connection.mockRespond(new Response(new ResponseOptions({
body:JSON.stringify(mockResponse)
})));
});

app.callApi().subscribe((response) => {
expect(response).toEqual(
{
body:”body from mock”
}
);
//call the handle function in component ,check for the console.log() messages inside the handleData function
app.handleData({
body:”body from mock”
});
});

}));

So thats it ,We have tested our $http calls using MockData

Unni Krishnan D
Unni Krishnan D

Written by Unni Krishnan D

Declare variables , not war! 😎

No responses yet