如何在指令上测试angular $ destroy事件?

时间:2014-01-20 23:13:03

标签: javascript angularjs angularjs-directive jasmine

指令(隔离范围,已转换,已替换)将掩码插入<body>

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

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

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

我试图通过范围内的简单广播来测试这种情况:

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);
});

知道为什么这不起作用?

1 个答案:

答案 0 :(得分:6)

错误是:该指令为多个叠加层创建<div id="mask"></div>倍。因此,在向DOM添加具有相同ID的多个<div>时,angular似乎存在问题。修好后,所有工作都按预期进行。

it('should remove mask when $destoryed', function () {
    scope.$destroy();
    expect($document.find('#mask').length).toBe(0);
});
相关问题