【发布时间】:2019-12-03 21:50:14
【问题描述】:
我必须在一个指令中向元素对象添加一个 $destroy 事件侦听器,该指令来自我在这个答案 Why isn't $destroy triggered when I call element.remove? 中找到的内容。
导致使用范围/元素创建的链接函数......
controller: "MyCtrl",
link: function(scope, element) {
element.on("$destroy", function() {
scope.func();
});
}
其中 func 是 MyCtrl 中定义的函数。
这适用于我想要的...但我无法测试 element.on("$destroy" 事件。
在我的指令测试中注入/模拟后,我创建了类似...的元素
this.$compile = $injector.get("$compile");
this.$rootScope = $injector.get("$rootScope");
this.$scope = this.$rootScope.$new();
this.template = "<my-dir></my-dir>";
this.initElement = function() {
this.element = this.$compile(this.template)(this.$scope);
return this.element;
};
尝试编写单元测试,破坏范围。元素破坏事件没有被触发......而且我的 this.element 没有它可以调用的 $destroy 函数。所以我不确定我是如何触发元素的 $destroy 事件的。
it("when element destroyed, call scope.func", function() {
this.$httpBackend.whenGET("app/my-dir.tpl.html").respond(200);
this.$scope.unsubscribeToMapMoveEvents = jasmine.createSpy("func");
this.initElement();
this.$scope.$destroy();
expect(this.$scope.func).toHaveBeenCalled();
});
我认为我在这个单元测试中面临的问题与我将这个逻辑从 ctrl 移动到指令链接函数的原因相同
对我如何在销毁工作流程中测试此元素有任何帮助吗?
【问题讨论】:
-
this 相关吗?
标签: javascript angularjs jasmine