Anup
Anup

Reputation: 9738

Angularjs Unit Test for Service

I am consuming a service for which i am writing unit test case. When i inject the service & call the function from controller, i do not get the data. I am beginner to write cases.

Here is my code.

StatesList Service

angular.module('myApp').factory('StatesList', ['$resource', function($resource) {
    return $resource('/api/states');
}]);    

Controller

$scope.statesList = function () {
            StatesList.query(function (states) {      
                // Brings all states
                 $scope.states = states;
            });
        };

Test

describe('States List', function () {
    var ctrl, scope, statesService;
    beforeEach(function () {
        module('myApp');
        inject(function ($rootScope, $controller, StatesList) {
            scope = $rootScope.$new();
            statesService = StatesList;
            ctrl = $controller('StatesCtrl', { $scope: scope, StatesList: statesService });
        });
    });

it('should have practice list to be null', function () {
        console.log('List of States');
        scope.statesList();
        console.log(scope.states); // I don't see any data here
        expect(scope.states).not.toBeNull();
    });

Output in WebStorm

'List of States'
undefined

Why the states don't get displayed. By using POSTMAN data can be seen.

Upvotes: 0

Views: 1689

Answers (1)

Ye Liu
Ye Liu

Reputation: 8976

StatesList.query() is an asynchronous http call, so you need to use mock $httpBackend service from ngMock module in your test. Add angular-mock.js to your test config, then try this:

describe('States List', function () {
    var ctrl, scope, statesService, $httpBackend;
    beforeEach(function () {
        module('myApp');
        inject(function ($rootScope, $controller, StatesList, _$httpBackend_) {
            scope = $rootScope.$new();
            statesService = StatesList;
            ctrl = $controller('StatesCtrl', { $scope: scope, StatesList: statesService});
            $httpBackend = _$httpBackend_;
        });
    });

    afterEach(function() {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });

    it('should have practice list to be null', function () {

        $httpBackend.expectGET('/api/states').respond([{ // ask mock $httpBackend to respond with fake data
            name: 'State 1'
        }, {
            name: 'State 2'
        }]);

        console.log('List of States');
        scope.statesList();

        $httpBackend.flush(); // flush the http request to send fake data back to StatesList.query()

        console.log(scope.states); // I don't see any data here
        expect(scope.states).not.toBeNull();
    });
});

Upvotes: 3

Related Questions