Injecting service into a mixin Ember2.3+

*爱你&永不变心* 提交于 2019-12-24 00:46:31

问题


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');
  }
})


来源:https://stackoverflow.com/questions/37190648/injecting-service-into-a-mixin-ember2-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!