Kratos
Kratos

Reputation: 1114

How to test $on event with parameters in Karma

I have the controller code:

$scope.$on('load', function (event) {
    $scope.getData();
    event.stopPropagation();
});

and the test code:

it('$on load', function(event) {
    var controller=createController();
    spyOn(scope, '$on').andCallThrough();// I have also tried to spy scope getData
    scope.$broadcast('load');
    expect(scope.$on).toHaveBeenCalledwith("load");
});

TypeError: event.stopPropagation is not a function

How can I define the parameters in the call from the Unit test?

Upvotes: 0

Views: 1012

Answers (1)

Sten Muchow
Sten Muchow

Reputation: 6711

Think of it in a different way...

If you fire the load event on the scope then u expect the getData to have been called...

Place a spy on the getData and then u can expect that function to have been called.

The way i have tested such thigns is to place the spy on the $broadcast.

 spyOn($scope, '$broadcast').and.callThrough();
 spyOn(event, 'preventDefault').and.callFake(function() {});

Then in the describe block

describe('load event', function() {

  it('should call getData method', function() {
      $scope.$broadcast('load');
      expect($scope.getData).toHaveBeenCalled();
    });

});

Upvotes: 2

Related Questions