-->

Injecting service into a mixin Ember2.3+

2019-07-24 10:18发布

问题:

I am having a problem with an error that pops up in my unit test suite when I try to check a service injected into Mixin since getOwner() has been added into Ember (deprecation guide here).

This is my mixin:

import Ember from 'ember';

export default Ember.Mixin.create({
    sha: Ember.inject.service('sha512'),
});

This is my basic unit test slightly changed after being generated by ember-cli:

import Ember from 'ember';
import DirtyRelationshipsDetectorMixin from 'xamoom-customer/mixins/dirty-relationships-detector';
import { module, test } from 'qunit';

module('Unit | Mixin | dirty relationships detector');

test('it works', function(assert) {
  let DirtyRelationshipsDetectorObject = Ember.Object.extend(DirtyRelationshipsDetectorMixin);
  let subject = DirtyRelationshipsDetectorObject.create();
  assert.ok(subject);
  assert.ok(subject.get('sha')); // problem occurs here
});

The error message I am getting is quite clear but I haven't found a solution:

Error: Assertion Failed: Attempting to lookup an injected property on an object without a container, ensure that the object was instantiated via a container.

The service is there when the app is running, it's just the test that fails. Ember 2.5.1 - Ember-CLI 2.5.0

回答1:

If you use Ember.getOwner(target) you can not just .create() the target, but inject the owner. with .create(owner.ownerInjection()). Typically an owner is an app instance.

Edit:

You are actually using getOwner when you use Ember.inject. Its like a shortcut for this:

sha: Ember.computed({
  get() {
    return Ember.getOwner(this).lookup('service:sha');
  }
})