【问题标题】:AngularJS - In Jasmine directive unit test, how can I trigger element.on("$destroy") event?AngularJS - 在 Jasmine 指令单元测试中,如何触发 element.on("$destroy") 事件?
【发布时间】: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 移动到指令链接函数的原因相同

对我如何在销毁工作流程中测试此元素有任何帮助吗?

【问题讨论】:

标签: javascript angularjs jasmine


【解决方案1】:

我的解决方案是使用此控制器定义的指令使用传入的 $rootScope,这会将其破坏到破坏不会启动的位置。

我改为将指令更改为使用它自己的空范围进行初始化,例如......

 controller: "MyCtrl",
 scope: {}

【讨论】:

    猜你喜欢
    • 2021-01-02
    • 1970-01-01
    • 2014-09-15
    • 2019-11-21
    • 2015-04-17
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多