最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to test angular $destroy event on a directive? - Stack Overflow

programmeradmin3浏览0评论

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($pile, _$document_, $rootScope, $injector) {
    rootScope = $injector.get('$rootScope');
    scope = $rootScope;
    $document = _$document_;
    mask = $document.find('#mask');
    element = $pile(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?

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($pile, _$document_, $rootScope, $injector) {
    rootScope = $injector.get('$rootScope');
    scope = $rootScope;
    $document = _$document_;
    mask = $document.find('#mask');
    element = $pile(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?

Share Improve this question edited Jan 20, 2014 at 23:40 e382df99a7950919789725ceeec126 asked Jan 20, 2014 at 23:13 e382df99a7950919789725ceeec126e382df99a7950919789725ceeec126 6,0015 gold badges34 silver badges56 bronze badges 2
  • can you show the directive and the entire spec? – Ilan Frumer Commented Jan 20, 2014 at 23:36
  • produces the same result. – e382df99a7950919789725ceeec126 Commented Jan 21, 2014 at 0:07
Add a ment  | 

1 Answer 1

Reset to default 6

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);
});
发布评论

评论列表(0)

  1. 暂无评论