简体   繁体   中英

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.

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();
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM