Quest
Quest

Reputation: 454

In Jasmine, how to test service response against static data

In angularJs app, I want to test the aboutService in jasmine. The About service returns data in the following format:

var companyObject = [{"CompanyName": "A", "Contact Number" : "123456789"}, {"CompanyName": "B", "Contact Number" : "1234567899"}]

angular
    .module('TestModule')
    .factory('aboutService', aboutService); 

    aboutService.$inject = ['$rootScope', '$http'];

    function homeService($rootScope, $http) {
        function getAboutData() {
            return $http({
                method: "GET",
                url: API URL,
            })
            .then(getAboutDataSuccess);

            function getAboutDataSuccess(results) {
                return results;//Data about company telephone contact number in array
            }
        }

        var aboutService = {
            getAboutData: getAboutData,
        };
    }

In aboutServiceSpec, I want to test if the data returned by API i.e an array length is greater than 0 and is equal to is equal to a variable companyObject

I have tried the following code with Jasmine, but it does not works.

    describe("Service: aboutService", function () {

        var aboutService, $httpBackend, $rootScope, response;
        var companyObject = [{ "CompanyName": "A", "Contact Number": "123456789" }, { "CompanyName": "B", "Contact Number": "1234567899" }]
        beforeEach(module('TestModule'));

        beforeEach(inject(function (_$httpBackend_, _aboutService_, _$rootScope_) {
            $httpBackend = _$httpBackend_;
            aboutService = _aboutService_;
            $rootScope = _$rootScope_;
        }));

        it('Should get about details of comapny', function () {
            $httpBackend.expectGET('URL');
            //Donot know how to go forward from here
        });
    });

Upvotes: 0

Views: 850

Answers (1)

crizzis
crizzis

Reputation: 10716

$httpBackend.expectGET('URL').respond(companyObject);
aboutService.getAboutData().then(function(result) {
    expect(result).toEqual(...); //or whatever expectation you want to test
});
$httpBackend.flush();

EDIT What this code does is the following:

  1. $httpBackend.expectGET(...).respond(...) defines an expectation of what requests the code under test and mocks the response to that request
  2. The expectations go to a .then block chained to the service returned by the promise (at this point, the promise of the $http request is not resolved yet)
  3. $httpBackend.flush() resolves the promise with the mock object specified earlier (only now are the expectations in the .then block fired). It also has the side effect of invalidating the test if the expected request has not been made

Upvotes: 1

Related Questions