我正在做一个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。任何帮助都是非常感谢的。
谢谢
发布于 2018-03-16 18:55:15
服务和控制器是在不同的时间创建的,这就是为什么你不能像你尝试的那样去做。就像$controller一样,已经创建了beforeEach(inject(function($controller) {服务--这也只是一个服务。
您应该在创建模块时模拟服务:
beforeEach(angular.mock.module('module', ($provide) => {
$provide.value(userService, {query: () => {}});
}));https://stackoverflow.com/questions/49312702
复制相似问题