我有以下......
app.controller('testCtrl', function(testService){
testService.doSomething();
});
app.service('testService', function(){
this.doSomething = function(){...};
});
我想使用Jasmine来确保doSomething只调用一次。我这样做似乎有些麻烦。
另外,我目前正在从像这样的编译元素中抓取我的控制器......
var element = angular.element('<my-test-directive />');
controller = view.controller('testCtrl');
如果适合这种格式化,那么额外的欣赏
更新
我试过了......
describe("Testing", function () {
var $rootScope,
$scope,
$compile,
testService,
view,
$controller;
beforeEach(module("app"));
function createController() {
return $controller('testCtrl', {
$scope: scope,
testService:testService
});
}
function SetUpScope(_$controller_, _$compile_, _$rootScope_, _testService_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
$controller = _$controller_;
testService = _testService_;
spyOn(testService, 'doSomething');
}
SetUpScope.$inject = ["$controller","$compile", "$rootScope", "testService"];
beforeEach(inject(SetUpScope));
it("On intitialization, the controller should register itself with the list service", function(done){
createController();
scope.$digest();
expect(workOrderService.doSomething).toHaveBeenCalled();
})
});
似乎有效
答案 0 :(得分:2)
最好单独测试控制器并使用Jasmine间谍:
spyOn(testService, 'doSomething');
expect(testService.doSomething.calls.count()).toEqual(0);
这样的事情应该在实际测试中起作用。
describe('testCtrl function', function() {
describe('testCtrl', function() {
var $scope, testService;
beforeEach(module('myApp'));
beforeEach(inject(function($rootScope, $controller, _testService_) {
$scope = $rootScope.$new();
testService = _testService_;
spyOn(testService, 'doSomething');
$controller('MyController', {$scope: $scope});
}));
it('should call testService.doSomething()', function() {
expect(testService.doSomething.calls.count()).toEqual(1);
});
});
});
这是一个快速的plunkr http://plnkr.co/edit/Swso4Y
根据您使用的Jasmine版本,您可能需要使用
expect(testService.doSomething.calls.length).toEqual(1);