0

Before adding my "needs" the controller looked like this

var MyController = Ember.ArrayController.extend({
    wat: function() {
        return true;
    }.property()
});

This allowed me to write really simple unit tests like so

test('wat always returns true ... huh', function() {
    var controller = new MyController();
    var wat = controller.get('wat');
    ok(wat);
});

But after I added a "needs" block like so ...

var MyController = Ember.ArrayController.extend({
    needs: 'application',
    wat: function() {
        return true;
    }.property()
});

The "new up" won't work and QUnit / ember is throwing an error like so

"Please be sure this controller was instantiated with a container"

Without saying "pull in / use ember-qunit" what other options do I have here? Can I simply slam in a "stub" to satisfy the container requirement?

Toran Billups
  • 27,111
  • 40
  • 155
  • 268

1 Answers1

1

With ember-qunit (which I'm not the biggest fan of) you can grab the controller using this.subject() and setting up the module like so:

moduleFor('controller:comments', 'Comments Controller', {
  needs: ['controller:post']
});

http://emberjs.com/guides/testing/testing-controllers/#toc_testing-controller-needs

If you weren't using Ember Qunit you could just use the container to fetch the controller (Initialized dependency not present when testing). Here's a helper:

Ember.Test.registerHelper('containerLookup',
  function(app, look) {
    return app.__container__.lookup(look);
  }
);

And you could use it easily like so:

test("root lists 3 colors", function(){
  var c = containerLookup('controller:foo');

  ok(c.get('controllers.bar.tr'));
  ok(!c.get('controllers.bar.fa'));
});

Example: http://emberjs.jsbin.com/tumeko/edit

Community
  • 1
  • 1
Kingpin2k
  • 47,277
  • 10
  • 78
  • 96
  • very cool - quick question that I'm unclear on w/ the 2nd approach you show here. Will this return the same instance each time (assuming I have that specific controller type configured as a singleton)? I'm looking for a "quick" and "easy" way to create truly new instances each time (is this possible when I use needs and want to skip out on ember-qunit?) – Toran Billups Oct 24 '14 at 13:02
  • It would return the same instance over and over, except we use `App.reset()` between each test which creates a new container giving us new controllers each time, example: http://emberjs.jsbin.com/tumeko/3/edit – Kingpin2k Oct 25 '14 at 05:59