【问题标题】:How should I check the sorted statement in jasmine or javascript我应该如何检查 jasmine 或 javascript 中的排序语句
【发布时间】:2012-06-04 08:51:20
【问题描述】:

我正在为 Backbone.Collection 编写规范。
我想使用 jasmine 在单元测试 javascript 中检查以下语句:

should the models be ordered by starting with the most recent.

模型中要检查的关键值是id(它是一个整数)。

例如,如果集合如下所示,则对其进行排序:

[
{id: 5, ….}, // the most recent
{id: 2, ...},
{id: 1, ...}
]

我的问题是:
1) 有没有茉莉花的方法来做这种检查?
2)如果没有,用javascript制作它的最佳方法是什么?也许使用下划线之类的库。

【问题讨论】:

  • 您想检查一个对象数组是否按其 id 排序?
  • @SiGanteng 是的,你明白了。我想检查对象数组是否按 id 排序

标签: javascript backbone.js underscore.js jasmine


【解决方案1】:

你可以做一个 for 循环,不确定是否有内置的检查你想要什么:

    var max = arr[0].id;
    var sorted = true;

    for(var i = 1; i < arr.length; i++) {
       if(max > arr[i].id) {
           sorted = false; break;
       }
    }

    alert(sorted);

【讨论】:

    【解决方案2】:

    大概您在收藏中设置了一个comparator,这将使您的收藏保持有序。

    在您的测试中,乱序创建 3 个项目,假设:

    collection = new MyCollection();
    collection.add({id: 1, bar: 'foo1'});
    collection.add({id: 5, bar: 'foo5'});
    collection.add({id: 3, bar: 'foo3'});
    

    然后确保比较器工作,变得像这样简单:

    expect(_.pluck(collection.models, 'id')).toEqual([5, 3, 1]);
    

    【讨论】:

      猜你喜欢
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-30
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      相关资源
      最近更新 更多