vendredi 29 mai 2015

Jasmine not recognizing spied on method called from asynchronous function resolution

From my controller, upon instantiation, I am calling an asynchronous method that calls a scope method:

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

My test is like so:

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()

I get the same error whether I call $digest() or not. I am expecting $digest() to resolve asyncMethod so that it calls myScopedMethod, but something is not right.

Aucun commentaire:

Enregistrer un commentaire