1

我的问题很简单,但很难回答......如何使用谷歌闭包工具将 $scope 注入到正在测试的 AngularJs 控制器。

控制器很简单,基本上就是通过_getOrganisations函数向服务器发起一个http请求

这是实际的控制器:

goog.provide 'MyModule.controllers.Menu'

MyModule.controllers.Menu = ($scope, $http, $location, SomeService) ->
  _getOrganisations = () ->

    $http({SomeRequestOptions})
      .success(_handleGetOrganisationsSuccessCallback)
      .error(_handleGetOrganisationsErrorCallback)

  _handleGetOrganisationsSuccessCallback = (result, status) ->
    $scope.organisations = result

  _handleGetOrganisationsErrorCallback = (err, status) ->
    [...]

  $scope.toggleMenu = () ->
    angular.element('.nav-collapse').collapse('toggle')

  _getOrganisations()

这是我尝试测试控制器的方法

describe 'menu controller', () =>

    result=
        org1 : ''
        org2 : ''
        org3 : ''

    beforeEach () ->
        goog.require 'MyModule.controllers.Menu'

        inject ($rootScope, $controller, $http, $httpBackend) ->
            scope = $rootScope.$new()
            httpBackend = $httpBackend
            httpBackend.whenGET({SomeRequestOptions}).respond result
            menuController = $controller new MyModule.controllers.Menu(), {$scope : scope, $http : $http}

    it 'should get organisations properly', () ->
        expect(scope.organisations).toEqual(result)

当我试图将我的实际控制器分配给 menuController 时,$scope 是未定义的......我在这里错过了什么?

4

1 回答 1

1

我可以在您的测试中看到代码的范围问题。我直接在代码中注释了。

describe 'menu controller', () =>

    result=
        org1 : ''
        org2 : ''
        org3 : ''

    beforeEach () ->
        goog.require 'MyModule.controllers.Menu'

        inject ($rootScope, $controller, $http, $httpBackend) ->
            # here you define a variable inside a function...
            scope = $rootScope.$new()
            httpBackend = $httpBackend
            httpBackend.whenGET({SomeRequestOptions}).respond result
            menuController = $controller new MyModule.controllers.Menu(), {$scope : scope, $http : $http}

    it 'should get organisations properly', () ->
        # here you try to access the variable from outside the function
        expect(scope.organisations).toEqual(result)

我还没有测试过代码,但我很确定这样的事情会解决它。根据这个帖子。http://odetocode.com/blogs/scott/archive/2013/06/10/simple-unit-tests-with-angularjs.aspx

describe 'menu controller', () =>
    scope = null
    result=
        org1 : ''
        org2 : ''
        org3 : ''

    beforeEach () ->
        goog.require 'MyModule.controllers.Menu'

        inject ($rootScope, $controller, $http, $httpBackend) =>
            scope = $rootScope.$new()
            httpBackend = $httpBackend
            httpBackend.whenGET({SomeRequestOptions}).respond result
            menuController = $controller new MyModule.controllers.Menu(), {$scope : scope, $http : $http}

    it 'should get organisations properly', () ->
        expect(scope.organisations).toEqual(result)
于 2013-06-26T18:59:32.473 回答