Unit testing controller using $ionicView.enter


#1

I’m trying to unit test a controller that uses $ionicView.enter like this

myControllers.controller('MyCtrl', [
'$scope',
function($scope) {
  'use strict';

  $scope.$on('$ionicView.enter', function(){
    $scope.myValue = 1;
  });

}]);

In my unit test I can spy on the event and check it’s been called, but it doesn’t then get into the function and set $scope.myValue. This is my test:

it('should do stuff', function () {
  spyOn(scope, '$on').and.callThrough();
  scope.$on('$ionicView.enter');

// this passes
  expect(scope.$on).toHaveBeenCalledWith('$ionicView.enter')
// this fails - scope.myValue is undefined
  expect(scope.myValue).toEqual(1);

});

I thought callThrough would call the code inside the function I’m spying on, but doesn’t seem to here.

Any help appreciated.


#2

The answer was to trigger the ionicView enter event after my controller set up in the test rather than try to spy on it.

beforeEach(inject(function($controller) {
  scope = $rootScope.$new();
 
  $controller('MyCtrl', {
    $scope: scope
  });

  scope.$emit('$ionicView.enter');

  scope.$digest();
}));