Jasmine无法识别从异步函数解析调用的方法

时间:2015-05-29 16:32:32

标签: angularjs unit-testing asynchronous jasmine

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

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,但有些事情是不对的。

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

范围不是间谍

使用

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

而不是

expect($scope.myScopedMethod)