Stubbing Services in EmberJS Integration Tests

Starting in Ember 2, the preferred way to test components is through integration tests. Integration tests allow you to declare the components using template syntax, and then intertact with the componen's externals using jquery. Ember's mantra of "Data down, actions up" makes integration tests an effective means of testing your components, since there is less need to manipulate component internals.

There are some cases though, where Ember components do require external dependences. The common way to represent these dependencies is through services. Services in Ember are singleton objects that are injected into components. They perform common tasks that require long lived state, that fall outside of the mechanisms of Ember Data.

Since a service might do things like interact with web sockets or keep up with your geo location, it might be necessary to stub or mock these services for your component integration tests. With unit tests, you can just set your mock directly on the component object, since you have access to its internals, but since integration tests deal with the component as a Black Box, you'll need an alernate way of overriding a service.

The way to stub a service is by using the built-in register function (available in integration tests via this.register) to register your stub as the service you want to replace.

Also, you can access your stub service instance within your test's this object by injecting it using this.inject.

Below is an example component that uses a location service to print city and country...

For the testcase, we'll stub the location service and just provide the city and country, then assert that they are reflected onscreen (see the first test below).

We also can now just interact with the location service stub via this.set, to test our component. For example, we can test that the displayed location changes when the service location changes, as shown in the second test below.

Some additional reading: