【问题标题】:Jasmine not recognizing spied on method called from asynchronous function resolutionJasmine 无法识别从异步函数解析中调用的方法
【发布时间】:2015-05-29 16:32:32
【问题描述】:

在我的控制器中,在实例化时,我正在调用一个调用范围方法的异步方法:

app.controller 'MyCtrl', ($scope,mySvc) ->
  ## do some initial stuff
  mySvc.asyncMethod
  .then (an_array) ->
    val = $scope.myScopedMethod

我的测试是这样的:

describe "my tests", () ->
  $controller = undefined
  $scope = undefined
  $q = undefined
  createController = undefined
  mySvc = undefined

  beforeEach inject ($controller, $rootScope, $q, _mySvc_) ->
    $scope = $rootScope.$new()
    mySvc = _mySvc_
    deferred = $q.defer()
    deferred.resolve []
    spyOn(mySvc,'asyncMethod').and.returnValue deferred.promise
    spyOn($scope, 'myScopedMethod').and.callThrough()
    createController = () ->
      return $controller('MyCtrl', {$scope: $scope, mySvc: mySvc})

  # this assertion works
  it "should call asyncMethod", () ->
    controller = createController()
    expect(mySvc.asyncMethod).toHaveBeenCalled()

  # this also works
  it "should define myScopedMethod", () ->
    controller = createController()
    expect(angular.isFunction($scope.myScopedMethod)).toBe true

  # this fails with 'Error: Expected a spy, but got Function.'
  it "should call $scope.myScopedMethod", () ->
    controller = createController()
    $scope.$digest()
    expect($scope.myScopedMethod).toHaveBeenCalled()

无论我是否调用$digest(),都会遇到同样的错误。我期待$digest() 解决asyncMethod 以便它调用myScopedMethod,但有些不对劲。

【问题讨论】:

    标签: angularjs unit-testing asynchronous jasmine


    【解决方案1】:

    当您尝试为其创建间谍时,$scope.myScopedMethod 似乎还不存在。

    你需要在函数创建后创建spy。希望它是作为控制器初始化的一部分创建的,所以您可以这样做:

    beforeEach inject ($controller, $rootScope, $q, _mySvc_) ->
        $scope = $rootScope.$new()
        mySvc = _mySvc_
        deferred = $q.defer()
        deferred.resolve []
        spyOn(mySvc,'asyncMethod').and.returnValue deferred.promise
        createController = () ->
            ctrl= $controller('MyCtrl', {$scope: $scope, mySvc: mySvc})
            spyOn($scope, 'myScopedMethod').and.callThrough()
            return ctrl
    

    【讨论】:

      【解决方案2】:

      范围不是间谍

      spy 是使用

      创建的
      var spy = spyOn($scope, 'myScopedMethod')
      

      expect($scope.myScopedMethod)
      

      【讨论】:

        猜你喜欢
        • 2019-04-11
        • 1970-01-01
        • 2013-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多