2

I have an Ember component...

Ember.Component.extend({
  onDidInsertElement: function(){
    var that = this;
    Ember.run.scheduleOnce('afterRender', () => {
      // Some code that sets up a jQuery plugin which attaches events etc
    });
  },
  onWillDestroyElement: function(){
    // Code that destroys the jQuery plugin (removing attached events etc)
  }
}

Here's my integration test:

test('it renders', function (assert) {
  this.render(hbs`{{my-component }}`);

  // Here some code to make sure the rendered state is ok

  // then...
  // ?? How to fire the "willDestroyElement" lifecycle hook?
}

Assuming I know how to check for the existence of the jQuery plugin events on the page (e.g. using the technique described here), how do I actually test the teardown logic in my integration test?

Community
  • 1
  • 1
sammy34
  • 5,312
  • 5
  • 29
  • 42

1 Answers1

4

You can use component.destroyElement (which mentions it will invoke willDestroyElement hook) or component.destroy.

Approach to do that without accessing component instance:

this.set('showComponent', true);
this.render(hbs(`{{if showComponent}}{{my-component}}{{/if}}`));

Then set:

this.set('showComponent', false);
Daniel Kmak
  • 18,164
  • 7
  • 66
  • 89
  • Ok, but how do I access, 'component' from an integration test? – sammy34 Nov 08 '15 at 14:28
  • 1
    Perhaps I should have mentioned that I'm using Ember 2.1 and the new approach to integration testing components (see here: http://guides.emberjs.com/v2.1.0/testing/testing-components/). Unless I'm missing something, in this new approach, the 'this' object has no methods 'destroyElement', 'destroy' and no property 'component' or anything similar I can see that would give me access to the component. – sammy34 Nov 08 '15 at 14:38
  • I might also add that I thought about "clearing" the render with `this.render(hbs`
    `)`, but that didn't seem to teardown the first component. I also looked for additional test hooks (like "beforeEach" and "afterEach" in the test setup logic), but again couldn't hook in anywhere where the component seemed to be destroyed. Looking for hints in the ember-qunit source also didn't help much. Made me think I'm perhaps going about this the wrong way...
    – sammy34 Nov 08 '15 at 15:17
  • 1
    Usually it's done in unit tests to test `willDestroyElement`, I think it should be possible in integration tests maybe using some conditions. Like `this.set('showComponent', true);`, `render(hbs('{{if showComponent}}{{my-component}}{{/if}}'))` and then setting `this.set('showComponent', false)`. You can try that. – Daniel Kmak Nov 08 '15 at 15:19
  • Bingo :). Great idea! Perhaps just update your answer with your latest suggestion for those coming in the future... – sammy34 Nov 08 '15 at 15:42
  • Done, I had to wait until you confirm. :P – Daniel Kmak Nov 08 '15 at 15:45