Angularjs服务单元测试

Angularjs Unit Test for Service

本文关键字:单元测试 服务 Angularjs      更新时间:2023-09-26

我正在消费一个服务,我正在为它编写单元测试用例。当注入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可以看到数据

StatesList.query()是一个异步http调用,因此您需要在测试中使用ngMock模块中的模拟$httpBackend服务。将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();
    });
});