Angularjs Jasmine未报告已调用角度控制器函数

Angularjs Jasmine未报告已调用角度控制器函数,angularjs,unit-testing,jasmine,Angularjs,Unit Testing,Jasmine,我在控制器上定义了一个方法,我正在尝试测试它是否被调用。我能够测试该方法是否已定义,但当我尝试测试它是否已被调用时,它会抱怨它预期已调用spy 这是我的控制器: myControllers.controller 'MyCtrl', ($scope) -> this.init = () -> doStuff() this.init() 这是我的测试套件: describe "testing myCtrl", () -> beforeEach "myControlle

我在控制器上定义了一个方法,我正在尝试测试它是否被调用。我能够测试该方法是否已定义,但当我尝试测试它是否已被调用时,它会抱怨它预期已调用spy

这是我的控制器:

myControllers.controller 'MyCtrl', ($scope) ->
  this.init = () -> doStuff()
  this.init()
这是我的测试套件:

describe "testing myCtrl", () ->
  beforeEach "myControllers"
  $controller = {}
  $scope = {}

  beforeEach inject (_$controller_,$rootScope) ->
    $controller = _$controller_
    $scope = $rootScope.$new()

  describe "MyCtrl", () ->
    beforeEach () -> 
      MyCtrl=$controller('MyCtrl',{$scope:$scope})

    it "should be defined", () -> # passes
      expect(MyCtrl).toBeDefined() 

    it "should define #init", () -> # passes
      expect(angular.isFunction(MyCtrl.init)).toBe true 

    it "should call #init", () -> # fails
      spyOn MyCtrl, 'init'
      expect(MyCtrl.init).toHaveBeenCalled()

最后一个断言导致错误:预期已调用spy init。

这是因为它会立即被调用,所以当您的测试命中时,它已经运行。创建MyCtrl的每个地方都会自动调用它。您必须以不同的结构进行测试。

我相信问题的答案是在我的控制器中没有init()函数。没有理由这样做。控制器中的顶级代码在实例化时运行,将其包装在init函数中是多余的

我应该如何构建它?我应该在断言中实例化控制器还是在每个断言之前创建间谍?