How to test on destroy scope

All we need is an easy explanation of the problem, so here it is.

How to unit testing an $destroy event of a Directive in angularjs?

I have the code in my directive:

scope.$on('$destroy', function () {
    //clean something
});

My test code:

it('on destroy',function(){
    scope.$destroy();
    scope.$digest();

    //expect everything done?
});

Any suggestion!

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You should test the code that is executed within the $destroy event. Here’s a contrived example using a controller:

Test

it('sets destroyed to true when the scope is destroyed', function() {
  // Arrange
  $scope.destroyed = false;

  // Act
  $scope.$destroy();

  // Assert
  expect($scope.destroyed).toBe(true);
});

Controller

app.controller('MainCtrl', function($scope) {
  $scope.$on('$destroy', function() {
    $scope.destroyed = true;
  });
});

Plunker here.

Method 2

You can select the DOM from the template of your directive and get the scope of it, then run $destroy().

Ex:

your tpl:

"<div id='tuna'></div>"

your test:

it('test on destroy', function(){
  var isolateScope = $(element).find('#tuna').eq(0).scope();
  isolateScope.$destroy();
})

Hope help you!

Method 3

Angular’s isolateScope is preferable to using jQuery. You’ve probably compiled the element in a beforeEach above your test like this:

myEl = '<div my-el>MY EL</div>';
scope = $rootScope.$new();
directiveElement = $compile(myEl)(scope);
scope.$digest();

Now in your test you can access the isolateScope and call $destroy:

var isolated = directiveElement.isolateScope();
isolated.$destroy();

Method 4

Here is what I do:

var destroyed = spyOn(scope, '$destroy').and.callThrough();
scope.$destroy();
expect(destroyed).toHaveBeenCalled();

unlike other answers I don’t have to create flag variables that only make sense for testing, also, it makes more sense to me to use Jasmine spyOn and callThrough to check if the function $destry is being successfully called.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply