简体   繁体   中英

AngularJS - In Jasmine directive unit test, how can I trigger element.on("$destroy") event?

I had to add a $destroy event listener to the element object in a directive from what I found with this answer Why isn't $destroy triggered when I call element.remove?

Resulting in a link function made with a scope/element....

  controller: "MyCtrl",
  link: function(scope, element) {
    element.on("$destroy", function() {
      scope.func();
    });
  }

Where func is a function defined in MyCtrl.

This works for what I want...but I'm having trouble testing the element.on("$destroy" event.

After injecting/mocking in my directive test, I create the element such like...

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

Trying to write a unit test, with destroying the scope. The element destroy event isn't triggered...and my this.element does not have a $destroy function it to call. So I'm not sure exactly how I trigger the element's $destroy event.

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

I think the problem I'm facing in this unit test is the same reason why I moved this logic from the ctrl to the directives link function

Any help on how I can test this element on destroy workflow?

My solution was the directive that is defined using this controller is using a $rootScope passed in, and that was breaking it to where the destroy wouldn't kick off.

I instead changed the directive to be initialized with it's own empty scope like....

 controller: "MyCtrl",
 scope: {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM