Colin Hanna
Colin Hanna

Reputation: 41

Initialized dependency not present when testing

I'm using ember-cli 0.0.35, and injecting a dependency onto my component via an initializer. It works great in development, but the property isn't present when I run tests. It appears that testing calls loadInitializers, but the dependency is not showing up on this.subject({});

I don't want to manually inject it for the tests. Is there a better way to handle this?

Initializer:

var FooServiceInitializer = {
  name: 'foo',
  initialize: function (container, application) {
   application.inject('component:foo', 'foo', 'service:foo');
  }
};
export default FooServiceInitializer;

Failing Test:

moduleForComponent('bar', 'Component: Bar', {
  setup: function() {
    App = startApp();
    component = this.subject({});
  },
  teardown: function () {
    Ember.run(App, App.destroy);
  }
});

test('Properties: foo', function() {
  // Make sure we injected the service
  ok(component.foo, 'foo is injected');
});

Upvotes: 4

Views: 1663

Answers (1)

Kingpin2k
Kingpin2k

Reputation: 47367

As I said before, it really lends itself to an integration test since you are testing the container at this point (and not the mini container created by ic-ajax).

Your real test is along the lines of this

test("root lists 3 colors", function(){
  var c = App.__container__.lookup('component:foo-bar');
  ok(c.foo.blah);
});

If you feel guilty about using the container during testing (which you shouldn't) you can create a helper to avoid having to fix it all over the place when/if an api changes in the future.

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

Make sure you define this before

App.injectTestHelpers();

and then your test would look like

test("root lists 3 colors", function(){
  var c = containerLookup('component:foo-bar');
  ok(c.foo.blah);
});

http://emberjs.jsbin.com/doxigu/edit

Upvotes: 2

Related Questions