Last Updated: February 27, 2017
· fr0gs

Inject Mock Service on every Ember test.

In other protips I explained two different ways to inject a service in a test. This last one will explain how to inject a mock service as a real service in each performed test, either acceptance, integration or unitary.

Say we have this simple mock service:

mockService = Ember.Service.extend
  mockFunction: ->
    'I mocked some stuff'

For an acceptance test:

module 'module-name', TestName', { 
beforeEach: ->
  application = startApp()
  application.register('service:mockservice', mockService);
  application.register('component', 'realService', 'service:mockservice')

afterEach: ->
  Ember.run application, 'destroy'

And for an integration/unit test:

moduleForComponent 'component-name', 'ComponentTestName', {
  unit: true
  beforeEach: ->
    @container.register('service:mockservice', mockService)
    @container.injection('component', 'realService', 'service:mockservice')

test 'it mocks the service', ->
expect 3
component = @subject()

component.set 'parentView',

equal component._state, 'preRender'

equal component._state, 'inDOM'

equal component.get('realService').mockFunction(), 'I mocked some stuff'
Say Thanks

1 Response
Add your response


Unit test solution does not work in Ember 2.1:
this.container.register is not a function

The updated code for injection would be :
beforeEach ->

@register 'service:mockservice', mockService

@inject.service 'realService', as: 'mockservice'
Source: https://guides.emberjs.com/v2.1.0/testing/testing-components/#toc_stubbing-services

10 months ago ·