单元测试解析服务的控制器

时间:2014-05-02 20:20:19

标签: javascript angularjs unit-testing

我正在尝试为我的家庭模块编写一个测试,但我一直收到一个错误,说'&34;未知提供商:服务"。如果我在home模块中更改resolveSomething以返回一个字符串我的应用程序工作,所以我知道我的决心是有效的。我只是在学习如何编写测试,所以任何建议都会受到高度赞赏。

服务

angular.module( 'services', [])
.factory('service', function(){ 
    return {
        'users' : function(id) {
            return id; 
        }
    }
}); 

主页的相关部分

angular.module('home', ['ui.router','services'])
.config(function config( $stateProvider, service) {
    $stateProvider.state( 'homeWithId', {
        url: '/home/:id',
        views: {
            "main": {
                controller: 'HomeCtrl',
                templateUrl: 'home/home.tpl.html'
            }
        },
        resolve:{
            resolveSomething: function() {
                return service.users(this.params.id);
            }
        }       
    })
})...

测试的相关部分......我认为

describe( 'Test home controller', function() {
    beforeEach( module( 'home' ) );
    beforeEach( module( 'services' ) );
    beforeEach(inject(function($injector) {
        $location = $injector.get('$location');
        $rootScope = $injector.get('$rootScope');
        $httpBackend = $injector.get('$httpBackend');
        $scope = $rootScope.$new();
        $state = $injector.get('$state');
        service = $injector.get('service');

        var $controller = $injector.get('$controller');

        createController = function() {
            return $controller('HomeCtrl', {
                '$scope': $scope,
                 resolveSomething: function() { console.log('resolveSomething'); },
                 service  : service
             });
        };
    ...

旁注...如果我只是在解析中返回一个字符串,我可以使用此测试配置访问控制器内的服务。

家庭控制器(工作和可测试)

.controller( 'HomeCtrl', ['$scope', 'resolveSomething','service', function( $scope, resolveSomething, service) {

    alert(service.users(1));
    ...

1 个答案:

答案 0 :(得分:0)

问题是service是服务,而不是提供者。当你致电module.config()时,你只能注射提供者;您的service尚未构建。我相信您需要做的是更改您的解析器以请求服务作为依赖项(我还没有使用UI状态提供程序,所以我可能错了):

angular.module('home', ['ui.router','services'])
.config(function config($stateProvider) {
    $stateProvider.state( 'homeWithId', {
        url: '/home/:id',
        views: {
            "main": {
                controller: 'HomeCtrl',
                templateUrl: 'home/home.tpl.html'
            }
        },
        resolve:{
            resolveSomething: function(service) {
                return service.users(this.params.id);
            }
        }       
    });
});
相关问题