EmberJS Service Injection for Unit Tests (Ember QUnit)
Asked Answered
E

1

9

Specs:

  • Ember 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 'alias' as example because I'm not allow to show actual code)

I've tried to initialize the service but during Ember Qunit tests, controllers do not have the services injected to them.

I've tried putting the injection in: init() instead of beforeEach, doesn't work either...

How do I inject it during unit tests?

I put break points in the debugger to see if my controllers have the service, it doesn't during tests. It's fine on normal ember serve, however.

Earthquake answered 7/12, 2015 at 1:39 Comment(0)
D
9

You don't have to import service. You have to include service in needs like below.

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

For eg:

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/unit/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 to run, Ember will generate a container with the controller test and service alias. So you can access the service properties with its name prefixed.

Dragone answered 15/12, 2015 at 5:6 Comment(1)
This solved my issue with ember-simple-auth session in unit testsEgalitarian

© 2022 - 2024 — McMap. All rights reserved.