Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test angular $destroy event on a directive?

The directive (isolated scope, transcluded, replaced) inserts a mask into the <body>.

var mask = angular.element('<div id="mask"></div>');

$document.find('body').append(mask);

scope.$on('$destroy', function() {
    mask.remove();
});

I am trying to test this case with a simple broadcast on the scope:

var $document, scope, element, rootScope;

beforeEach(inject(function($compile, _$document_, $rootScope, $injector) {
    rootScope = $injector.get('$rootScope');
    scope = $rootScope;
    $document = _$document_;
    mask = $document.find('#mask');
    element = $compile(angular.element('<overlay id="derp"></overlay>'))(scope);
}));

it('should remove mask when casting the $destory event', function (done) {
    scope.$broadcast('$destroy');
    scope.$digest();
    expect($document.find('#mask').length).toBe(0);
});

Any idea why this doesn't work?

like image 584
e382df99a7950919789725ceeec126 Avatar asked Jan 20 '14 23:01

e382df99a7950919789725ceeec126


1 Answers

The mistake was: the directive creates the <div id="mask"></div> multiple for mulitple overlays. So angular seems to have problems when adding multiple <div>'s with the same ID to the DOM. After fixing this, all worked as expected.

it('should remove mask when $destoryed', function () {
    scope.$destroy();
    expect($document.find('#mask').length).toBe(0);
});
like image 106
e382df99a7950919789725ceeec126 Avatar answered Oct 19 '22 00:10

e382df99a7950919789725ceeec126