【问题标题】:Testing Angular 1 service测试 Angular 1 服务
【发布时间】:2018-08-25 01:06:28
【问题描述】:

我正在做一个 Angular 1 项目,我正在设置单元测试。 所以,我需要测试一个服务,它的名字是“appSecurity”。此服务中的方法使用来自名为“userService”的服务的预加载用户数据。 “appSecurity”服务仅从 userService 引用此用户数据以做出适当的安全决策。

下面是部分appSecurity服务,方便大家理解:

function appSecurity($log, $http, $state, $q, localStorageService, userService, grcRoutes, appRolesConstant, controlAssessmentService) {
    appSecurity.routeToErrorPageIfNotFullAccessRoleInCM = function () {
        var controlRegisterRoles = _.find(userService.currentUser.controlRegisterUsers, function (controlRegisterUser) {
        var controlRegisterUserRole = controlRegisterUser.applicationRoles[0];
        return controlRegisterUserRole.name === appRolesConstant.FullAccess;
      });
   };
}

如您所见,该服务有许多依赖项,如 $log、$http、$state、$q、localStorageService、userService、grcRoutes、appRolesConstant、controlAssessmentService。其中之一是 userService,它预先加载了用户数据。

基本上,我希望能够在 appSecurity 服务中注入模拟的 userService,这样我就可以测试它的方法而不必担心它的依赖数据。下面是一个对控制器执行相同操作的示例。

beforeEach(inject(function($controller) {
  $scope = $rootScope.$new();

  userService = {
    query: function() {
      queryDeferred = $q.defer();
      return {$promise: queryDeferred.promise};
    }
  }

spyOn(userService, 'query').andCallThrough();

// controller injected with mocked service. How can I do the same with a 
//service. In this case I want to instantiate appSecurity service like this 
//with inject mocked userService. 
  $controller('BreakfastCtrl', {
    '$scope': $scope,
    'userService': userService 
  });
}));

我们可以使用模拟依赖注入创建控制器的方法,有没有一种方法可以使用模拟注入创建服务。我尝试在上面的代码中用 $service 替换 $controller 但它没有用。

我想这样做,

$service('appSecurityService', {
   '$scope': $scope,
   'userService': userService 
});

但是在 angular-mocks 中找不到 $service。 非常感谢任何帮助。

谢谢

【问题讨论】:

    标签: javascript angularjs unit-testing angular-mock


    【解决方案1】:

    服务和控制器是在不同的时间创建的,这就是为什么你不能像你尝试的那样去做。在beforeEach(inject(function($controller) { 行已经创建了服务,例如$controller - 这也只是一个服务。

    您应该在创建模块时模拟服务:

    beforeEach(angular.mock.module('module', ($provide) => {
                    $provide.value(userService, {query: () => {}});
            }));
    

    【讨论】:

      猜你喜欢
      • 2023-01-30
      • 2019-05-06
      • 2013-11-08
      • 2014-02-09
      • 2017-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多