Mocking Services when writing Ember.js Tests


UPDATE:

Since writing this there have been some significant changes to make this easier.

The first is that https://github.com/switchfly/ember-test-helpers now includes a way to do this for Ember 1.11 +
https://github.com/switchfly/ember-test-helpers/pull/96

Even better thanks to the Registry / Container reform in Ember 2 + it should “just work” https://github.com/emberjs/ember.js/issues/11174


A lot of work has been done on Ember’s testing story & if you haven’t already seen it I’d really recommend taking the time to watch @toranb’s Emberconf 2015 presentation where he TDD’s his way live through various features. For me, it’s a fantastic example of what makes Ember such a powerful framework and is very inspiring to improve your test coverage.

One of the less obvious aspects of writing tests in Ember is how you can mock services, something which as controllers become deprecated appears to be more and more relevant. In the most recent episode of Ember Weekend they talk about their experience & in the Introduction to Ember screencast by @jgwhite it also crops up.

Therefore I thought it could be helpful to show one way of doing this that is pretty straightforward.

Imagine we have a simple service that we inject into our route and test like this…

The example service gets injected into our route automatically, we haven’t neeeded to write an initializer for this. It just works.

Mocking this out is not so easy though, the guys of Ember Weekend take an approach which they explain in their podcast and you can see their code on github that involves using some ‘very private APIs’.

Another approach that was inspired by @jgwhite was to create an initializer for the service and to then pass in when testing a mocked service to be used in preference.

You can see this illustrated in code here.

One change to note is that to avoid any potential conflicts between the automatic service injection as ‘example’ I’ve named the service in the initializer & when injecting it as ‘exampleService’ instead — I would be very happy to hear if this is the correct approach, but it seems to work well.

You can clone a working example of this from the github repo in case something isn’t clear in these snippets.

Thanks for reading, @chrisdmasters / @EmberLinks

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.