How create a unit test for view in Ember CLI that renders the view (like components)

I can’t find a single example in google for unit test of views in Ember CLI that renders the view (without renders all app).

I wanna this for test events registered inside of didInserElement hook.

For components i can find docs very easy. For render the component in a test with moduleForComponent just do:

test("component test", function(){
  var component = this.subject(),
  element = this.append();
  ok(element.is('.clickable'), 'has the clickable class');
});

But how i do this for views?

I use this way to render only the view in unit tests:

tests/unit/views/main-test.js:

import Ember from 'ember';
import { test, moduleFor } from 'ember-qunit';

var view;

moduleFor('view:main', 'MainView', {
  needs: ['template:main'],
  setup: function() {
    var controller = Ember.ObjectController.extend({
      //mockController if needs
    }).create();
    view = this.subject({
      controller: controller,
      templateName: 'main',
    });
    Ember.run(function() {
      view.appendTo('#ember-testing');
    });
  },
  teardown: function() {
    Ember.run(function() {
      view.destroy();
    });
  },
});

test("didInsertElement", function(){
  var element = Ember.$('.main');
  var controller = view.get('controller');

  var eventForPressCtrlAltM = Ember.$.Event( "keydown", { which: 77, altKey: true, ctrlKey: true } );

  Ember.run(function() {
    element.trigger(eventForPressCtrlAltM);
  });
  strictEqual(/* ... */);
});
1 Like

With latest ember versions this does not work: If the view’s template has an {{outlet}} the test will fail with

undefined must be a subclass or an instance of Ember.View, not

when view.appendTo("#ember-testing") is called.