我有一个控制器首先调用的服务。我无法找到用jasmine 1.3测试它的方法。
我无法窥探productService实例' fetch'方法,因为在编写测试时(我认为)已经运行了所有初始化代码。
控制器:
(function () {
'use strict';
angular.module('my.module')
.controller('MyController', [
'$scope',
'$rootScope',
'ProductService',
'broadcastEventsConstants',
'OrganizationSvc',
function ($scope, $rootScope, ProductService, broadcastEventsConstants, OrganizationSvc) {
$scope.productService = new ProductService();
var fetchFresh = function(org) {
$scope.productService.filterOptions.page = 0;
$scope.productService.org = org;
$scope.productService.fetch({append: false, reselect: false});
}
var init = function() {
if(_.has(OrganizationSvc.selectedOrganization, 'id')) {
fetchFresh(OrganizationSvc.selectedOrganization);
}
};
init();
}]);
})();
}
试验:
'use strict';
describe('MyController', function () {
var $scope;
var $rootScope;
var $controller;
var MyController
var ProductService;
var broadcastEventsConstants;
var OrganizationSvc;
beforeEach(function () {
module('my.module', function ($provide) {
$provide.factory('OrganizationSvc', function () {
return {
selectedOrganization: {
id: 1,
getList: function (endpoint, options) {
console.log('i was called with ', endpoint, options);
}
}
};
});
$provide.factory('ProductService', function () {
function ProductService() {
this.filterOptions = {};
this.fetch = function () {
return [];
};
}
return ProductService;
});
$provide.constant('broadcastEventsConstants', {
ORGANIZATION_CHANGED: 'organizationChanged'
});
});
inject(function (_$rootScope_, _$controller_, _$q_, _$timeout_, _OrganizationSvc_, _ProductService_, _broadcastEventsConstants_) {
$rootScope = _$rootScope_;
$scope = _$rootScope_.$new();
$controller = _$controller_;
ProductService = _ProductService_;
broadcastEventsConstants = _broadcastEventsConstants_;
OrganizationSvc = _OrganizationSvc_;
});
ManagePublishProductController = $controller('ManagePublishProductController', {
$scope: $scope
});
});
describe('initiating phase', function () {
it('should make a call to fetch if the org is set on the org service', function () {
spyOn($scope.productService, 'fetch');
$scope.$digest();
expect($scope.productService.fetch).toHaveBeenCalled();
});
});
});
答案 0 :(得分:0)
据推测,ProductService
在其原型上声明了fetch
。您应该能够监视原型方法,如下所示:
spyOn(ProductService.prototype, 'fetch');
如果不是这种情况,请附上ProductService
看起来的草图。