测试具有依赖关系的angularjs

时间:2016-07-21 09:58:15

标签: angularjs unit-testing ionic-framework jasmine karma-jasmine

我对AngularJS的测试很新,我很困惑。我有一个依赖于依赖于值的服务的控制器。我已经为控制器编写了非常基本的测试,只是为了掌握它,当我没有将值注入服务时它们都会通过。但是,当我将值注入服务时,我在控制器的所有测试中都会出现Unknown provider错误。

我的代码如下:

控制器

'use strict';
angular.module('app')
    .controller('testController', function($scope, testService) {

        $scope.$on('$ionicView.enter', function() {
            $scope.setup();
        });

        $scope.testFunction = function() {
            $scope.result = 1;
        };

        $scope.setup = function() {
            testService.superAwesomeFunction();
            $scope.enterValue = 1;
        };

    });

服务

'use strict';
angular.module('app')
    .service('testService', ['URLRoute', function(URLRoute) {

        var superAwesomeFunction = function() {
            var URLRequest = URLRoute;
            console.log(URLRequest);
        };

        return {
            superAwesomeFunction: superAwesomeFunction
        };
    }]);

'use strict';
angular.module('app')
    .value('URLRoute', {
        url: 'https://abcdefghijklmnop.com/api',
    });

test.controller.test.js

'use strict';
describe('testController', function() {
    beforeEach(module('app'));

    var $controller, 
        $rootScope, 
        $scope;

    beforeEach(inject(function(_$controller_, _$rootScope_) {
        $controller = _$controller_;
        $rootScope = _$rootScope_;
        $scope = $rootScope.$new();

        $controller('testController', { 
            $scope: $scope
        });
    }));

    describe('$scope.$on(ionicView.enter)', function() {
        it ('$scope.$on calls $ionicView.enter', function() {
            spyOn($scope, '$on').and.callThrough();
            $scope.$on('$ionicView.enter');
            expect($scope.$on).toHaveBeenCalledWith('$ionicView.enter');
        });
    });

    describe('$scope.testFunction', function() {
        it('Sets the value of result to 1', function() {
            $scope.testFunction();
            expect($scope.result).toEqual(1);
        });
    });

    describe('$scope.setup', function() {
        it('Sets up stuff for the view after it has loaded', function() {
            $scope.setup();
            expect($scope.enterValue).toEqual(1);
        });
    });


});

现在测试运行时,我得到的错误是:

Unknown provider: URLRouteProvider <- URLRoute <- testService

任何帮助表示赞赏,对此非常困惑。

1 个答案:

答案 0 :(得分:0)

试试这个:

'use strict';
angular.module('app')
.service('testService', [ function(URLRoute) {

    var superAwesomeFunction = function() {
        var URLRequest = URLRoute;
        console.log(URLRequest);
    };

    return {
        superAwesomeFunction: superAwesomeFunction
    };
}]);

来自:lostechies