【问题标题】:Unit testing a controller that resolves a service对解析服务的控制器进行单元测试
【发布时间】:2023-03-12 16:05:01
【问题描述】:

我正在尝试为我的主模块编写一个测试,但我不断收到一条错误消息,提示“未知提供者:服务”。如果我在我的 home 模块中更改 resolveSomething 以返回一个字符串,我的应用程序可以工作,所以我知道我的 resolve 工作正常。我只是在学习如何编写测试,所以任何建议都将不胜感激。

服务

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));
    ...

【问题讨论】:

    标签: javascript angularjs unit-testing


    【解决方案1】:

    问题在于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);
                }
            }       
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-20
      • 1970-01-01
      • 1970-01-01
      • 2012-11-19
      • 2015-09-16
      • 2017-06-02
      • 2020-11-27
      • 2019-03-20
      相关资源
      最近更新 更多