Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing $scope.$on AngularJS

Hello Everyone I am struggling at testing a $.on function and I am looking for any suggestions or help on this:

controller

  $scope.$on("sampleFilesSelected", function(event, args) {
                $scope.sampleFiles = args.newSampleFiles;
            }); 

spec

describe('Testing a $.on', function() {
  var $scope = null;
  var ctrl = null;


  beforeEach(module('test'));

  it('should invoke myEvent when "myEvent" broadcasted', inject(function($rootScope, $controller) {
    $scope = $rootScope.$new();

    ctrl = $controller('MainCtrl', {
      $scope: $scope
    });

    $scope.$broadcast('myEvent');
    expect($scope.sampleFilesSelected).toBe(true);
  }));
});

error

TypeError: Unable to get property 'newSampleFiles' of undefined or null reference
        undefined
like image 431
user2402107 Avatar asked Jul 20 '26 02:07

user2402107


2 Answers

You should pass a value to your event, call a $digest before your assertion :

$scope.$broadcast('myEvent', { 'newSampleFiles' : true } );
$scope.$digest();
expect($scope.sampleFilesSelected).toBe(true);
like image 142
mathieu Avatar answered Jul 21 '26 16:07

mathieu


this code ...

$scope.$broadcast('myEvent');

is not passing any args and so args.newSampleFiles throws an error because args is undefined

you need to pass args - how you do that I don't know

However, I would say ... unit testing is used for testing controller code not really for testing event handling. Your example is a bit of an edge case. I would be tempted to test the event handling use E2E testing and protractor.

I would refactor as follows ...

$scope.$on("sampleFilesSelected", function(event, args) {
                $scope.sampleFiles = args.newSampleFiles;
            });

would become ...

$scope.myFunction = function(event, args) {
   $scope.sampleFiles = args.newSampleFiles;
}

$scope.$on("sampleFilesSelected", $scope.myFunction);

and i would unit test $scope.myFunction. And leave the testing of $scope.$on to E2E protractor testing.

Hope that helps

like image 43
danday74 Avatar answered Jul 21 '26 17:07

danday74



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!