EmberJS Service Injection for Unit Tests (Ember QUnit)

Specifications:

  • Amber Version: 1.13.8
  • node: 0.10.33
  • npm: 2.13.4

I have

import Alias from "../../../services/alias"; .... moduleFor("controller:test", "Controller: test", { integration: true, beforeEach: function() { this.register('service:alias', Alias, {singleton: true}); this.inject.service('alias', { as: 'alias' }); this.advanceReadiness(); }, }); ... test('Alias Alias Alias ', function(assert) { var controller = this.subject(); //sample function controller.send("test"); assert.equal(true, controller.alias.get("alias"), "alias should be true"); }); 
(Using an "alias" as an example, because I cannot show the actual code)

I tried to initialize the service, but during the Ember Qunit tests, the controllers do not have the services that were added to them.

I tried to insert an injection in: init () instead of beforeEach, it doesn't work and ...

How do I embed it during unit tests?

I set breakpoints in the debugger to see if my controllers have this service, but not during the tests. However, this is normal on an ordinary ember.

+8
unit-testing qunit ember-cli ember-data
source share
1 answer

You do not need to import the service. You must enable the service in need, as shown below.

 moduleFor("controller:test", { needs: ['service:alias'] }); 

For example,

service / alias.js

 Em.service.extend({ name: 'john' }); 

controllers / test.js

 Em.Controller.extend({ alias: Em.service.inject(), test: function() { alert(this.get('alias.name'); } }); 

Tests / block / controllers / test-test.js

 moduleFor('controller:test', { needs: ['service:store'] }); test('Alias Alias Alias', function(assert) { var controller = this.subject(); assert.equal(controller.get('store.name'), 'john); }); 

For this test, Ember will create a container with a controller test and service alias . This way, you can access the properties of the service with a name prefix.

+7
source share

All Articles