我想测试以下函数实际上是使用茉莉花调用该控制器的初始化。似乎使用间谍是一种方式,它只是不能像我所期望的那样工作,当我把它的期望在“它”块被调用。我想知道是否有一种特殊的方法来检查在调用范围函数中是否调用了某些东西,但是在控制器本身中。
App.controller('aCtrl',[ '$scope',function($scope){ $scope.loadResponses = function(){ //do something } $scope.loadResponses(); }]);
// spec文件
describe('test spec',function(){ beforeEach( //rootscope assigned to scope,scope injected into controller,controller instantiation.. the expected stuff spyOn(scope,'loadResponses'); ); it('should ensure that scope.loadResponses was called upon instantiation of the controller',function(){ expect(scope.loadResponses).toHaveBeenCalled(); }); });
您需要根据创建的范围自己初始化控制器。问题是,您需要重新构建代码。你不能监视一个不存在的函数,但你需要在调用函数之前先spyOn。
原文链接:https://www.f2er.com/angularjs/144279.html$scope.loadResponses = function(){ //do something } // <-- You would need your spy attached here $scope.loadResponses();
由于您不能这样做,您需要将$ scope.loadResponses()调用到别处。
var scope; beforeEach(inject(function($controller,$rootScope) { scope = $rootScope.$new(); $controller('aCtrl',{$scope: scope}); scope.$digest(); })); it("should have been called",function() { spyOn(scope,"loadResponses"); scope.doTheStuffThatMakedLoadResponsesCalled(); expect(scope.loadResponses).toHaveBeenCalled(); });