本文介绍了将服务注入mixin Ember2.3 +的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 getOwner()注入Mixin的服务时,单元测试套件中弹出错误,我遇到了问题$ c>已添加到Ember中(弃用指南)。

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).

这是我的混音

import Ember from 'ember';

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

这是我的基本单元测试,由ember-cli生成后略有变化:

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:

应用程序运行时服务就在那儿,只是测试失败了。
Ember 2.5.1-Ember-CLI 2.5.0

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

推荐答案

如果使用 Ember.getOwner(target)您不能只是 .create()目标,而是使用 .create(owner.ownerInjection())。通常,所有者是一个应用程序实例。

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.

编辑:

您实际上是使用 Ember.inject 时使用 getOwner 。就像这样的快捷方式:

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

这篇关于将服务注入mixin Ember2.3 +的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:50