Today I Learned

hashrocket A Hashrocket project

[Ember Integration tests] `this.inject` rocks!

When I first saw the inject helper in Ember Integration tests I had assumed that I would use these to stub services for testing purposes.

@rwjblue quickly pointed out to me that this is/was not their intent. And that for that I should use register for that purpose.

Instead what they are useful for is to utilize functions (helpers) found on services. Something like i18n.t. For our example I'll just assume we have a service named foo with a function upcase. And our component takes a string and presents it upcased in a span.

With that in mind we can do something like this in our integration test:

moduleForComponent('some-thing', {
  integration: true
});

test('does a thing', function(assert) {
  this.inject.service('foo');
  this.render(hbs`{{some-thing textToRender='foo' }}`);
  let result = this.foo.upcase('foo'); // 'FOO'
  
  assert.equal(this.$('span').text(), result, 'should upcase textToRender');
});

Alright, I know what you are thinking. This is a little contrived. And it is, but let's examine what this is doing a little more closely.

We injected foo to make it available in the testing context with this.foo or this.get('foo'). That's super sweet!

Need a service helper function you can do it with this.inject!

Learn more here

Cheers

See More #emberjs TILs