Today I Learned

hashrocket A Hashrocket project

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

In Ember Integration tests it sometimes becomes necessary to stub / mock services. Luckily, we have a few options open to us.

Let's assume that we have a service called foo that implements an API method called bar. We'll also assume that when you click on our components' a tag you trigger an action that calls the foo service's API.

Whoa, still with me?

keanu

Alright. Let's dive in!

import FooService from '<app-name>/services/foo';

moduleForComponent('some-thing',  {
  integration: true,
  beforeEach(){ 
    // extending in case the foo service has other responsibilities
    this.register('foo', FooService.extend({
      bar() { assert.ok(true); } 
    }));
  }
});

test('blah', function(assert) {
  assert.expect(1);
  this.render(hbs`{{some-thing}}`);
  this.$('a').click();
});

That wasn't so bad. We're simply ensuring that the FooService's bar API function gets called. I think this is a wonderful way to handle this.

You can find more information about this.register (and how to stub/mock services) here:

Stubbing Services Ember.js Guides

See More #emberjs TILs