Angularjs服务单元测试

时间:2014-03-17 11:40:24

标签: javascript node.js angularjs unit-testing jasmine

我正在使用我正在编写单元测试用例的服务。当我注入service&从controller调用该函数,我没有得到data。我是初学者写案例。

这是我的代码。

StatesList服务

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

控制器

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

测试

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

WebStorm中的输出

'List of States'
undefined

为什么州没有显示出来。通过使用POSTMAN数据可以看出。

1 个答案:

答案 0 :(得分:3)

StatesList.query()是异步http调用,因此您需要在测试中使用来自$httpBackend模块的模拟ngMock服务。将angular-mock.js添加到测试配置中,然后尝试:

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