【问题标题】:Ember.js component integration test: How to work with global injections and nested components?Ember.js 组件集成测试:如何使用全局注入和嵌套组件?
【发布时间】:2017-01-10 17:43:42
【问题描述】:

场景:我想使用真实服务my-service 集成测试组件 A。我有一个将服务全局注入所有组件的初始化程序:application.inject('component', 'myService', 'service:my-service');。组件 A 在其模板中使用组件 B,并且它们都在其模板中使用 myService

如何重新创建全局注入?没有完整的应用程序,所以我无法导入和运行真正的初始化程序,因为我没有所需的参数。 this.inject.service 不起作用,因为它将其注入测试上下文,而不是全局应用程序上下文。

我可以更改所有组件的模板以将服务一直链接起来:{{b-component myService=myService}},然后

this.render(hbs`{{a-component myService=myService}}`);

但这是最后的手段。我还可以摆脱全局注入并手动注入每个组件。这也是不得已的办法。

我已追踪到 https://github.com/emberjs/ember.js/issues/12277 对此问题的讨论。它几乎已实施,但随后因大测试统一https://github.com/emberjs/rfcs/pull/119 而关闭。在我们等待大测试统一期间,现在有什么解决方案吗?

【问题讨论】:

    标签: javascript ember.js dependency-injection ember-testing ember-components


    【解决方案1】:

    https://stackoverflow.com/users/1157494/robert-jackson 的提示下,我找到了丢失的部分。您可以在测试上下文中查找所有者,这是您需要提供给初始化程序的缺失参数:

    import { initialize } from 'my-app/initializers/my-initializer';
    
    // ...
    
    beforeEach() {
      initialize(Ember.getOwner(this));
    }
    

    现在您的所有组件都具有所需的全局注入!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-25
      • 2017-07-19
      相关资源
      最近更新 更多