Test Online REST API using Karma & Jasmine

Today we are going to add test for Online REST API. For that we are using JSONPlaceholder Fake Online REST API.

Let’s start the testing. First of all we are going to write our test for angular.factory called jsonplaceholder.spec.js.

describe('JSON Placeholder API Service', function () {
    var API_ENDPOINT = 'https://jsonplaceholder.typicode.com';

    beforeEach(angular.mock.module('api.jsonplaceholder'));

    beforeEach(inject(function (_JsonPlaceholderApi_, _httpBackend_, _q_){
        JsonPlaceholderApi = _JsonPlaceholderApi_;
        httpBackend = _httpBackend_;
        q = _q_;
    }));

    it(' Should Exists', function (){
        expect(JsonPlaceholderApi).toBeDefined();
    });
});

Now if you run karma start you will see something like that:
screen-shot-2017-11-06-at-11-19-06-am

which means, we haven’t defined our angular module with factory. Lets defined that:

(function (){
    'use strict';
    angular.module('api.jsonplaceholder', []).factory('JsonPlaceholderApi', jsonPlaceholderApi);
    jsonPlaceholderApi.inject = ['http', 'q'];

    function jsonPlaceholderApi(http, $q) {
        return this;
    };
}());

This time you will see something like that:
screen-shot-2017-11-06-at-11-21-10-am

Now, lets make a GET call to REST API end point /posts. It will return 100 post item as JSON response. On Success, here we will mock the response with a mockObject which length is 3.

describe('JSON Placeholder API Service', function () {
    var API_ENDPOINT = 'https://jsonplaceholder.typicode.com',
        mockResponse = [
            {
                "userId": 1,
                "id": 1,
                "title": "sunt aut facere repellat provident occaecati excepturi",
                "body": "quia et suscipitnsuscipit recusandae consequuntur expedita"
            },
            {
                "userId": 1,
                "id": 2,
                "title": "qui est esse",
                "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea "
            },
            {
                "userId": 1,
                "id": 3,
                "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
                "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi "
            }];

    beforeEach(angular.mock.module('api.jsonplaceholder'));

    beforeEach(inject(function (_JsonPlaceholderApi_, _httpBackend_, _q_){
        JsonPlaceholderApi = _JsonPlaceholderApi_;
        httpBackend = _httpBackend_;
        q = _q_;
    }));

    it(' Should Exists', function (){
        expect(JsonPlaceholderApi).toBeDefined();
    });

    describe('GET /Post ', function () {
        var result;

        beforeEach(function () {
            result = {};
            spyOn(JsonPlaceholderApi, 'getAll').and.callThrough();
        });

        it('should return All Posts ', function () {
            httpBackend.whenGET(API_ENDPOINT + '/posts')
                                 .respond(200,q.when(mockResponse));

            expect(JsonPlaceholderApi.getAll).not.toHaveBeenCalled();

            JsonPlaceholderApi.getAll().then(function (response) {
                result = response;
            });

            $httpBackend.flush();
            expect(JsonPlaceholderApi.getAll).toHaveBeenCalled();
            expect(result.length).toEqual(3);
            expect(Object.keys(result[0]).length).toEqual(4);
        });

    });
});

Now, if you run your test you will see an error with getAll method is not defined. Let’s define that method:

(function (){
    'use strict';
    angular.module('api.jsonplaceholder', []).factory('JsonPlaceholderApi', jsonPlaceholderApi);
    jsonPlaceholderApi.inject = ['http', 'q'];

    function jsonPlaceholderApi(http, q) {
        var jsonPlaceholderApi = {},
            API_ENDPOINT = 'https://jsonplaceholder.typicode.com';

        jsonPlaceholderApi.getAll = function () {
            returnhttp.get(API_ENDPOINT + '/posts').then(function (res){
                return res.data;
            });
        };
        return jsonPlaceholderApi;
    };
}());

That’s it. Now you can write as many test as you want.

Test Yourself
– write a test to find an item using following REST API GET /posts/1;

it('should return a POST When called with a valid Id', function (){
    //@TODO: write your test
});