Jasmine SpyOn hasBeenCalled on function link not working (Angular)

In my Angular controller, I have implemented a listener that calls a function by reference:

$scope.$on('$destroy', vm.popoverChooseProfile.remove);

      

I used the karma and jasmine test.

  it('should remove the popover the scope is destroy', function() {
    var vm = createController();

    vm.popoverChooseProfile = MOCK_POPOVER;

    spyOn(vm.popoverChooseProfile, 'remove');

    $scope.$destroy();
    expect(vm.popoverChooseProfile.remove).toHaveBeenCalled();
  });

      

The test above does not work, but if I terminate the vm.popoverChooseProfile.remove link in the anonymous function, the test succeeds

$scope.$on('$destroy', function() {

vm.popoverChooseProfile.remove();

});

      

In my opinion the anonymous function is useless in this case. Do you have any idea how to make the spy work with the help function?

thank

+3


source to share


1 answer


When you assign a handler to an event, you are giving it a reference to a function, not an object property. This is the same as writing:

var handler = vm.popoverChooseProfile.remove;
$scope.$on('$destroy', handler);

      

Jasmine, to check if a function has been called, replaces the original property with its own function, which retains the status if it was called, and calls the original function if necessary.



So, at the time the event happens, the vm.popoverChooseProfile.remove handler! ==, so the test fails.

To fix this, you must either do a wrapper like you do, or install spyOn before installing an event listener.

+1


source







All Articles