我无法对在返回$ resource的服务上使用resolve的控制器进行单元测试。在控制器内部,我等待服务的承诺在将其设置为我的$ scope变量之前解析,但我不确定如何模拟resolve属性以使测试通过。
我正在尝试测试的控制器
angular.module('app')
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/settings', {
templateUrl: '/views/settings.html',
controller:'SettingsCtrl',
resolve: {
settings: ['SettingsService', function (SettingsService) {
return SettingsService.get(
function(response) {
console.log('success');
},
function(err) {
console.log('error');
}
)
}]
}
});
}])
.controller('SettingsCtrl', ['$scope', 'settings',
function($scope, settings) {
settings.$promise.then(
function(data) {
$scope.settings = data;
},
function (err) {
console.log('error');
console.log(err);
}
);
}]);
和服务
angular.module('app')
.factory('SettingsService', ['$resource', function ($resource) {
return $resource('/api/settings', {}, {
get: {method: 'GET'},
});
}]);
返回的当前尝试无法读取未定义的属性。
describe('Testing SettingsController with resolve', function() {
beforeEach(module('app'));
beforeEach(inject(function(_$rootScope_, $controller, _$q_) {
$scope = _$rootScope_.$new();
$rootScope = _$rootScope_;
$q = _$q_;
mockSettingsService = function() {
deferred = _$q_.defer();
return {$promise: deferred.promise};
}
$controller('SettingsCtrl', {
$scope: $scope,
settings: mockSettingsService
});
}));
it('should retrieve the data', function() {
var mockResponse = {data: 'data'}
deferred.resolve(mockResponse);
$rootScope.$apply();
expect($scope.settings).toEqual(mockResponse);
});
});
我知道如何通过模拟服务来测试具有服务注入的控制器,但我仍然想知道如何测试解析返回promise的服务的控制器。