将.findBy()与Ember数据填充的数组控制器一起使用

Bee*_*eez 6 qunit ember.js ember-data

背景

我正在编写一些功能测试来测试我的路由器正在导航并正确加载我的模型.到目前为止,这很好 - 即使是在这个问题上.

为了你的享受,我创造了一个小提琴.这是行不通的-我从来没有多少运气用的jsfiddle和灰烬,尽管分叉的@wagenet.但是它有更多的源代码来帮助我全面了解我的情况.

我最大的抱怨

所以我最大的抱怨是以下代码无法从控制器检索具有已知id的元素:

var controller = App.__container__.lookup("controller:postsNew");
var type1Option = controller.get("controllers.types").findBy("TYPE1");
Run Code Online (Sandbox Code Playgroud)

我在setupController钩子里做了类似的事情并且它有效.但这是在我的应用程序的上下文中,所以看起来更像是这样:

setupController: function(controller, model) {
    this._super(controller, model);
    this.controllerFor("types").findBy("TYPE1");
}
Run Code Online (Sandbox Code Playgroud)

但即使这样也不行了!我现在也在我的应用程序之外工作 - 在一个qunit测试中.所以我必须App.__container__.lookup()根据我读过的所有内容使用.

根?

我发现的controller.length是未定义的 - 导致.findBy()失败.这些项目存在于数组中......至少,我可以通过这样做看到它们controller.toArray().

临时解决方案

以下是我要做的事情:

var controller = App.__container__.lookup("controller:postsNew");
var type1Option = null;
$.each(controller.get("controllers.types").toArray(), function(index, elm) {
    if (elm.get("id") === "TYPE1") {
        type1Option = elm;
        return true;
    }
});
Run Code Online (Sandbox Code Playgroud)

这显然不是那么干净.

所以,问题

  • .findBy()打破?
  • 我做错.findBy()了吗?
  • 你怎么用.findBy()

Kin*_*n2k 8

findBy需要2个参数,要测试的属性键和要查找的值(如果未传入则默认为true).从本质上讲,你正在寻找与属性的模型TYPE1true

你可能想要这样做

findBy("id", "TYPE1")
Run Code Online (Sandbox Code Playgroud)

http://emberjs.com/api/classes/Ember.Array.html#method_findBy

返回具有与传递的值匹配的属性的第一个项目.您可以使用目标值传递可选的第二个参数.否则,这将匹配任何计算结果为true的属性.