Search code examples
ember.jsember-testing

How to new up a controller that "needs" application?


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?


Solution

  • 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