Monthly Archives: November 2014

Unit testing $scope.$on(‘$viewContentLoaded’) on an Angularjs Controller

TL;DR = call

$scope.$broadcast('$viewContentLoaded');

in your unit test. This will call your

$scope.$on('$viewContentLoaded', function () {}); 

method in your controller

If you have a Controller that has a method that is not fired until the view is loaded you will have a method similar to the following:

    $scope.$on('$viewContentLoaded', function () {
       SomeService.callMethod(params);
    });

The test case needs to wire in the $scope into your test like below

describe('when the campaign controller is initialized', function () {

 beforeEach( function() {
    $scope.$broadcast('$viewContentLoaded');
 } );

 it('should call the getAllCampaignTypes service call', function () {
     expect(mockedSomeService.callMethods).toHaveBeenCalledWith( ... );
 });

The Most important thing is the call to $scope.$broadcast(‘$viewContentLoaded’);