PageRenderTime 1183ms CodeModel.GetById 221ms app.highlight 785ms RepoModel.GetById 161ms app.codeStats 1ms

/vendor/backbone/test/collection.js

https://gitlab.com/shuoyang/lodash
JavaScript | 1368 lines | 1214 code | 147 blank | 7 comment | 14 complexity | 7e119270e516cb5697199d57775566fe MD5 | raw file
   1(function() {
   2
   3  var a, b, c, d, e, col, otherCol;
   4
   5  module("Backbone.Collection", {
   6
   7    setup: function() {
   8      a         = new Backbone.Model({id: 3, label: 'a'});
   9      b         = new Backbone.Model({id: 2, label: 'b'});
  10      c         = new Backbone.Model({id: 1, label: 'c'});
  11      d         = new Backbone.Model({id: 0, label: 'd'});
  12      e         = null;
  13      col       = new Backbone.Collection([a,b,c,d]);
  14      otherCol  = new Backbone.Collection();
  15    }
  16
  17  });
  18
  19  test("new and sort", 9, function() {
  20    var counter = 0;
  21    col.on('sort', function(){ counter++; });
  22    equal(col.first(), a, "a should be first");
  23    equal(col.last(), d, "d should be last");
  24    col.comparator = function(a, b) {
  25      return a.id > b.id ? -1 : 1;
  26    };
  27    col.sort();
  28    equal(counter, 1);
  29    equal(col.first(), a, "a should be first");
  30    equal(col.last(), d, "d should be last");
  31    col.comparator = function(model) { return model.id; };
  32    col.sort();
  33    equal(counter, 2);
  34    equal(col.first(), d, "d should be first");
  35    equal(col.last(), a, "a should be last");
  36    equal(col.length, 4);
  37  });
  38
  39  test("String comparator.", 1, function() {
  40    var collection = new Backbone.Collection([
  41      {id: 3},
  42      {id: 1},
  43      {id: 2}
  44    ], {comparator: 'id'});
  45    deepEqual(collection.pluck('id'), [1, 2, 3]);
  46  });
  47
  48  test("new and parse", 3, function() {
  49    var Collection = Backbone.Collection.extend({
  50      parse : function(data) {
  51        return _.filter(data, function(datum) {
  52          return datum.a % 2 === 0;
  53        });
  54      }
  55    });
  56    var models = [{a: 1}, {a: 2}, {a: 3}, {a: 4}];
  57    var collection = new Collection(models, {parse: true});
  58    strictEqual(collection.length, 2);
  59    strictEqual(collection.first().get('a'), 2);
  60    strictEqual(collection.last().get('a'), 4);
  61  });
  62
  63  test("clone preserves model and comparator", 3, function() {
  64    var Model = Backbone.Model.extend();
  65    var comparator = function(model){ return model.id; };
  66
  67    var collection = new Backbone.Collection([{id: 1}], {
  68      model: Model,
  69      comparator: comparator
  70    }).clone();
  71    collection.add({id: 2});
  72    ok(collection.at(0) instanceof Model);
  73    ok(collection.at(1) instanceof Model);
  74    strictEqual(collection.comparator, comparator);
  75  });
  76
  77  test("get", 6, function() {
  78    equal(col.get(0), d);
  79    equal(col.get(d.clone()), d);
  80    equal(col.get(2), b);
  81    equal(col.get({id: 1}), c);
  82    equal(col.get(c.clone()), c);
  83    equal(col.get(col.first().cid), col.first());
  84  });
  85
  86  test("get with non-default ids", 5, function() {
  87    var col = new Backbone.Collection();
  88    var MongoModel = Backbone.Model.extend({idAttribute: '_id'});
  89    var model = new MongoModel({_id: 100});
  90    col.add(model);
  91    equal(col.get(100), model);
  92    equal(col.get(model.cid), model);
  93    equal(col.get(model), model);
  94    equal(col.get(101), void 0);
  95
  96    var col2 = new Backbone.Collection();
  97    col2.model = MongoModel;
  98    col2.add(model.attributes);
  99    equal(col2.get(model.clone()), col2.first());
 100  });
 101
 102  test('get with "undefined" id', function() {
 103    var collection = new Backbone.Collection([{id: 1}, {id: 'undefined'}]);
 104    equal(collection.get(1).id, 1);
 105  }),
 106
 107  test("update index when id changes", 4, function() {
 108    var col = new Backbone.Collection();
 109    col.add([
 110      {id : 0, name : 'one'},
 111      {id : 1, name : 'two'}
 112    ]);
 113    var one = col.get(0);
 114    equal(one.get('name'), 'one');
 115    col.on('change:name', function (model) { ok(this.get(model)); });
 116    one.set({name: 'dalmatians', id : 101});
 117    equal(col.get(0), null);
 118    equal(col.get(101).get('name'), 'dalmatians');
 119  });
 120
 121  test("at", 1, function() {
 122    equal(col.at(2), c);
 123  });
 124
 125  test("pluck", 1, function() {
 126    equal(col.pluck('label').join(' '), 'a b c d');
 127  });
 128
 129  test("add", 14, function() {
 130    var added, opts, secondAdded;
 131    added = opts = secondAdded = null;
 132    e = new Backbone.Model({id: 10, label : 'e'});
 133    otherCol.add(e);
 134    otherCol.on('add', function() {
 135      secondAdded = true;
 136    });
 137    col.on('add', function(model, collection, options){
 138      added = model.get('label');
 139      opts = options;
 140    });
 141    col.add(e, {amazing: true});
 142    equal(added, 'e');
 143    equal(col.length, 5);
 144    equal(col.last(), e);
 145    equal(otherCol.length, 1);
 146    equal(secondAdded, null);
 147    ok(opts.amazing);
 148
 149    var f = new Backbone.Model({id: 20, label : 'f'});
 150    var g = new Backbone.Model({id: 21, label : 'g'});
 151    var h = new Backbone.Model({id: 22, label : 'h'});
 152    var atCol = new Backbone.Collection([f, g, h]);
 153    equal(atCol.length, 3);
 154    atCol.add(e, {at: 1});
 155    equal(atCol.length, 4);
 156    equal(atCol.at(1), e);
 157    equal(atCol.last(), h);
 158
 159    var coll = new Backbone.Collection(new Array(2));
 160    var addCount = 0;
 161    coll.on('add', function(){
 162        addCount += 1;
 163    });
 164    coll.add([undefined, f, g]);
 165    equal(coll.length, 5);
 166    equal(addCount, 3);
 167    coll.add(new Array(4));
 168    equal(coll.length, 9);
 169    equal(addCount, 7);
 170  });
 171
 172  test("add multiple models", 6, function() {
 173    var col = new Backbone.Collection([{at: 0}, {at: 1}, {at: 9}]);
 174    col.add([{at: 2}, {at: 3}, {at: 4}, {at: 5}, {at: 6}, {at: 7}, {at: 8}], {at: 2});
 175    for (var i = 0; i <= 5; i++) {
 176      equal(col.at(i).get('at'), i);
 177    }
 178  });
 179
 180  test("add; at should have preference over comparator", 1, function() {
 181    var Col = Backbone.Collection.extend({
 182      comparator: function(a,b) {
 183        return a.id > b.id ? -1 : 1;
 184      }
 185    });
 186
 187    var col = new Col([{id: 2}, {id: 3}]);
 188    col.add(new Backbone.Model({id: 1}), {at:   1});
 189
 190    equal(col.pluck('id').join(' '), '3 1 2');
 191  });
 192
 193  test("can't add model to collection twice", function() {
 194    var col = new Backbone.Collection([{id: 1}, {id: 2}, {id: 1}, {id: 2}, {id: 3}]);
 195    equal(col.pluck('id').join(' '), '1 2 3');
 196  });
 197
 198  test("can't add different model with same id to collection twice", 1, function() {
 199    var col = new Backbone.Collection;
 200    col.unshift({id: 101});
 201    col.add({id: 101});
 202    equal(col.length, 1);
 203  });
 204
 205  test("merge in duplicate models with {merge: true}", 3, function() {
 206    var col = new Backbone.Collection;
 207    col.add([{id: 1, name: 'Moe'}, {id: 2, name: 'Curly'}, {id: 3, name: 'Larry'}]);
 208    col.add({id: 1, name: 'Moses'});
 209    equal(col.first().get('name'), 'Moe');
 210    col.add({id: 1, name: 'Moses'}, {merge: true});
 211    equal(col.first().get('name'), 'Moses');
 212    col.add({id: 1, name: 'Tim'}, {merge: true, silent: true});
 213    equal(col.first().get('name'), 'Tim');
 214  });
 215
 216  test("add model to multiple collections", 10, function() {
 217    var counter = 0;
 218    var e = new Backbone.Model({id: 10, label : 'e'});
 219    e.on('add', function(model, collection) {
 220      counter++;
 221      equal(e, model);
 222      if (counter > 1) {
 223        equal(collection, colF);
 224      } else {
 225        equal(collection, colE);
 226      }
 227    });
 228    var colE = new Backbone.Collection([]);
 229    colE.on('add', function(model, collection) {
 230      equal(e, model);
 231      equal(colE, collection);
 232    });
 233    var colF = new Backbone.Collection([]);
 234    colF.on('add', function(model, collection) {
 235      equal(e, model);
 236      equal(colF, collection);
 237    });
 238    colE.add(e);
 239    equal(e.collection, colE);
 240    colF.add(e);
 241    equal(e.collection, colE);
 242  });
 243
 244  test("add model with parse", 1, function() {
 245    var Model = Backbone.Model.extend({
 246      parse: function(obj) {
 247        obj.value += 1;
 248        return obj;
 249      }
 250    });
 251
 252    var Col = Backbone.Collection.extend({model: Model});
 253    var col = new Col;
 254    col.add({value: 1}, {parse: true});
 255    equal(col.at(0).get('value'), 2);
 256  });
 257
 258  test("add with parse and merge", function() {
 259    var collection = new Backbone.Collection();
 260    collection.parse = function(attrs) {
 261      return _.map(attrs, function(model) {
 262        if (model.model) return model.model;
 263        return model;
 264      });
 265    };
 266    collection.add({id: 1});
 267    collection.add({model: {id: 1, name: 'Alf'}}, {parse: true, merge: true});
 268    equal(collection.first().get('name'), 'Alf');
 269  });
 270
 271  test("add model to collection with sort()-style comparator", 3, function() {
 272    var col = new Backbone.Collection;
 273    col.comparator = function(a, b) {
 274      return a.get('name') < b.get('name') ? -1 : 1;
 275    };
 276    var tom = new Backbone.Model({name: 'Tom'});
 277    var rob = new Backbone.Model({name: 'Rob'});
 278    var tim = new Backbone.Model({name: 'Tim'});
 279    col.add(tom);
 280    col.add(rob);
 281    col.add(tim);
 282    equal(col.indexOf(rob), 0);
 283    equal(col.indexOf(tim), 1);
 284    equal(col.indexOf(tom), 2);
 285  });
 286
 287  test("comparator that depends on `this`", 2, function() {
 288    var col = new Backbone.Collection;
 289    col.negative = function(num) {
 290      return -num;
 291    };
 292    col.comparator = function(a) {
 293      return this.negative(a.id);
 294    };
 295    col.add([{id: 1}, {id: 2}, {id: 3}]);
 296    deepEqual(col.pluck('id'), [3, 2, 1]);
 297    col.comparator = function(a, b) {
 298      return this.negative(b.id) - this.negative(a.id);
 299    };
 300    col.sort();
 301    deepEqual(col.pluck('id'), [1, 2, 3]);
 302  });
 303
 304  test("remove", 5, function() {
 305    var removed = null;
 306    var otherRemoved = null;
 307    col.on('remove', function(model, col, options) {
 308      removed = model.get('label');
 309      equal(options.index, 3);
 310    });
 311    otherCol.on('remove', function(model, col, options) {
 312      otherRemoved = true;
 313    });
 314    col.remove(d);
 315    equal(removed, 'd');
 316    equal(col.length, 3);
 317    equal(col.first(), a);
 318    equal(otherRemoved, null);
 319  });
 320
 321  test("add and remove return values", 13, function() {
 322    var Even = Backbone.Model.extend({
 323      validate: function(attrs) {
 324        if (attrs.id % 2 !== 0) return "odd";
 325      }
 326    });
 327    var col = new Backbone.Collection;
 328    col.model = Even;
 329
 330    var list = col.add([{id: 2}, {id: 4}], {validate: true});
 331    equal(list.length, 2);
 332    ok(list[0] instanceof Backbone.Model);
 333    equal(list[1], col.last());
 334    equal(list[1].get('id'), 4);
 335
 336    list = col.add([{id: 3}, {id: 6}], {validate: true});
 337    equal(col.length, 3);
 338    equal(list[0], false);
 339    equal(list[1].get('id'), 6);
 340
 341    var result = col.add({id: 6});
 342    equal(result.cid, list[1].cid);
 343
 344    result = col.remove({id: 6});
 345    equal(col.length, 2);
 346    equal(result.id, 6);
 347
 348    list = col.remove([{id: 2}, {id: 8}]);
 349    equal(col.length, 1);
 350    equal(list[0].get('id'), 2);
 351    equal(list[1], null);
 352  });
 353
 354  test("shift and pop", 2, function() {
 355    var col = new Backbone.Collection([{a: 'a'}, {b: 'b'}, {c: 'c'}]);
 356    equal(col.shift().get('a'), 'a');
 357    equal(col.pop().get('c'), 'c');
 358  });
 359
 360  test("slice", 2, function() {
 361    var col = new Backbone.Collection([{a: 'a'}, {b: 'b'}, {c: 'c'}]);
 362    var array = col.slice(1, 3);
 363    equal(array.length, 2);
 364    equal(array[0].get('b'), 'b');
 365  });
 366
 367  test("events are unbound on remove", 3, function() {
 368    var counter = 0;
 369    var dj = new Backbone.Model();
 370    var emcees = new Backbone.Collection([dj]);
 371    emcees.on('change', function(){ counter++; });
 372    dj.set({name : 'Kool'});
 373    equal(counter, 1);
 374    emcees.reset([]);
 375    equal(dj.collection, undefined);
 376    dj.set({name : 'Shadow'});
 377    equal(counter, 1);
 378  });
 379
 380  test("remove in multiple collections", 7, function() {
 381    var modelData = {
 382      id : 5,
 383      title : 'Othello'
 384    };
 385    var passed = false;
 386    var e = new Backbone.Model(modelData);
 387    var f = new Backbone.Model(modelData);
 388    f.on('remove', function() {
 389      passed = true;
 390    });
 391    var colE = new Backbone.Collection([e]);
 392    var colF = new Backbone.Collection([f]);
 393    ok(e != f);
 394    ok(colE.length === 1);
 395    ok(colF.length === 1);
 396    colE.remove(e);
 397    equal(passed, false);
 398    ok(colE.length === 0);
 399    colF.remove(e);
 400    ok(colF.length === 0);
 401    equal(passed, true);
 402  });
 403
 404  test("remove same model in multiple collection", 16, function() {
 405    var counter = 0;
 406    var e = new Backbone.Model({id: 5, title: 'Othello'});
 407    e.on('remove', function(model, collection) {
 408      counter++;
 409      equal(e, model);
 410      if (counter > 1) {
 411        equal(collection, colE);
 412      } else {
 413        equal(collection, colF);
 414      }
 415    });
 416    var colE = new Backbone.Collection([e]);
 417    colE.on('remove', function(model, collection) {
 418      equal(e, model);
 419      equal(colE, collection);
 420    });
 421    var colF = new Backbone.Collection([e]);
 422    colF.on('remove', function(model, collection) {
 423      equal(e, model);
 424      equal(colF, collection);
 425    });
 426    equal(colE, e.collection);
 427    colF.remove(e);
 428    ok(colF.length === 0);
 429    ok(colE.length === 1);
 430    equal(counter, 1);
 431    equal(colE, e.collection);
 432    colE.remove(e);
 433    equal(null, e.collection);
 434    ok(colE.length === 0);
 435    equal(counter, 2);
 436  });
 437
 438  test("model destroy removes from all collections", 3, function() {
 439    var e = new Backbone.Model({id: 5, title: 'Othello'});
 440    e.sync = function(method, model, options) { options.success(); };
 441    var colE = new Backbone.Collection([e]);
 442    var colF = new Backbone.Collection([e]);
 443    e.destroy();
 444    ok(colE.length === 0);
 445    ok(colF.length === 0);
 446    equal(undefined, e.collection);
 447  });
 448
 449  test("Colllection: non-persisted model destroy removes from all collections", 3, function() {
 450    var e = new Backbone.Model({title: 'Othello'});
 451    e.sync = function(method, model, options) { throw "should not be called"; };
 452    var colE = new Backbone.Collection([e]);
 453    var colF = new Backbone.Collection([e]);
 454    e.destroy();
 455    ok(colE.length === 0);
 456    ok(colF.length === 0);
 457    equal(undefined, e.collection);
 458  });
 459
 460  test("fetch", 4, function() {
 461    var collection = new Backbone.Collection;
 462    collection.url = '/test';
 463    collection.fetch();
 464    equal(this.syncArgs.method, 'read');
 465    equal(this.syncArgs.model, collection);
 466    equal(this.syncArgs.options.parse, true);
 467
 468    collection.fetch({parse: false});
 469    equal(this.syncArgs.options.parse, false);
 470  });
 471
 472  test("fetch with an error response triggers an error event", 1, function () {
 473    var collection = new Backbone.Collection();
 474    collection.on('error', function () {
 475      ok(true);
 476    });
 477    collection.sync = function (method, model, options) { options.error(); };
 478    collection.fetch();
 479  });
 480
 481  test("ensure fetch only parses once", 1, function() {
 482    var collection = new Backbone.Collection;
 483    var counter = 0;
 484    collection.parse = function(models) {
 485      counter++;
 486      return models;
 487    };
 488    collection.url = '/test';
 489    collection.fetch();
 490    this.syncArgs.options.success();
 491    equal(counter, 1);
 492  });
 493
 494  test("create", 4, function() {
 495    var collection = new Backbone.Collection;
 496    collection.url = '/test';
 497    var model = collection.create({label: 'f'}, {wait: true});
 498    equal(this.syncArgs.method, 'create');
 499    equal(this.syncArgs.model, model);
 500    equal(model.get('label'), 'f');
 501    equal(model.collection, collection);
 502  });
 503
 504  test("create with validate:true enforces validation", 3, function() {
 505    var ValidatingModel = Backbone.Model.extend({
 506      validate: function(attrs) {
 507        return "fail";
 508      }
 509    });
 510    var ValidatingCollection = Backbone.Collection.extend({
 511      model: ValidatingModel
 512    });
 513    var col = new ValidatingCollection();
 514    col.on('invalid', function (collection, error, options) {
 515      equal(error, "fail");
 516      equal(options.validationError, 'fail');
 517    });
 518    equal(col.create({"foo":"bar"}, {validate:true}), false);
 519  });
 520
 521  test("a failing create returns model with errors", function() {
 522    var ValidatingModel = Backbone.Model.extend({
 523      validate: function(attrs) {
 524        return "fail";
 525      }
 526    });
 527    var ValidatingCollection = Backbone.Collection.extend({
 528      model: ValidatingModel
 529    });
 530    var col = new ValidatingCollection();
 531    var m = col.create({"foo":"bar"});
 532    equal(m.validationError, 'fail');
 533    equal(col.length, 1);
 534  });
 535
 536  test("initialize", 1, function() {
 537    var Collection = Backbone.Collection.extend({
 538      initialize: function() {
 539        this.one = 1;
 540      }
 541    });
 542    var coll = new Collection;
 543    equal(coll.one, 1);
 544  });
 545
 546  test("toJSON", 1, function() {
 547    equal(JSON.stringify(col), '[{"id":3,"label":"a"},{"id":2,"label":"b"},{"id":1,"label":"c"},{"id":0,"label":"d"}]');
 548  });
 549
 550  test("where and findWhere", 8, function() {
 551    var model = new Backbone.Model({a: 1});
 552    var coll = new Backbone.Collection([
 553      model,
 554      {a: 1},
 555      {a: 1, b: 2},
 556      {a: 2, b: 2},
 557      {a: 3}
 558    ]);
 559    equal(coll.where({a: 1}).length, 3);
 560    equal(coll.where({a: 2}).length, 1);
 561    equal(coll.where({a: 3}).length, 1);
 562    equal(coll.where({b: 1}).length, 0);
 563    equal(coll.where({b: 2}).length, 2);
 564    equal(coll.where({a: 1, b: 2}).length, 1);
 565    equal(coll.findWhere({a: 1}), model);
 566    equal(coll.findWhere({a: 4}), void 0);
 567  });
 568
 569  test("Underscore methods", 16, function() {
 570    equal(col.map(function(model){ return model.get('label'); }).join(' '), 'a b c d');
 571    equal(col.any(function(model){ return model.id === 100; }), false);
 572    equal(col.any(function(model){ return model.id === 0; }), true);
 573    equal(col.indexOf(b), 1);
 574    equal(col.size(), 4);
 575    equal(col.rest().length, 3);
 576    ok(!_.include(col.rest(), a));
 577    ok(_.include(col.rest(), d));
 578    ok(!col.isEmpty());
 579    ok(!_.include(col.without(d), d));
 580    equal(col.max(function(model){ return model.id; }).id, 3);
 581    equal(col.min(function(model){ return model.id; }).id, 0);
 582    deepEqual(col.chain()
 583            .filter(function(o){ return o.id % 2 === 0; })
 584            .map(function(o){ return o.id * 2; })
 585            .value(),
 586         [4, 0]);
 587    deepEqual(col.difference([c, d]), [a, b]);
 588    ok(col.include(col.sample()));
 589    var first = col.first();
 590    ok(col.indexBy('id')[first.id] === first);
 591  });
 592
 593  test("reset", 16, function() {
 594    var resetCount = 0;
 595    var models = col.models;
 596    col.on('reset', function() { resetCount += 1; });
 597    col.reset([]);
 598    equal(resetCount, 1);
 599    equal(col.length, 0);
 600    equal(col.last(), null);
 601    col.reset(models);
 602    equal(resetCount, 2);
 603    equal(col.length, 4);
 604    equal(col.last(), d);
 605    col.reset(_.map(models, function(m){ return m.attributes; }));
 606    equal(resetCount, 3);
 607    equal(col.length, 4);
 608    ok(col.last() !== d);
 609    ok(_.isEqual(col.last().attributes, d.attributes));
 610    col.reset();
 611    equal(col.length, 0);
 612    equal(resetCount, 4);
 613
 614    var f = new Backbone.Model({id: 20, label : 'f'});
 615    col.reset([undefined, f]);
 616    equal(col.length, 2);
 617    equal(resetCount, 5);
 618
 619    col.reset(new Array(4));
 620    equal(col.length, 4);
 621    equal(resetCount, 6);
 622  });
 623
 624  test ("reset with different values", function(){
 625    var col = new Backbone.Collection({id: 1});
 626    col.reset({id: 1, a: 1});
 627    equal(col.get(1).get('a'), 1);
 628  });
 629
 630  test("same references in reset", function() {
 631    var model = new Backbone.Model({id: 1});
 632    var collection = new Backbone.Collection({id: 1});
 633    collection.reset(model);
 634    equal(collection.get(1), model);
 635  });
 636
 637  test("reset passes caller options", 3, function() {
 638    var Model = Backbone.Model.extend({
 639      initialize: function(attrs, options) {
 640        this.model_parameter = options.model_parameter;
 641      }
 642    });
 643    var col = new (Backbone.Collection.extend({ model: Model }))();
 644    col.reset([{ astring: "green", anumber: 1 }, { astring: "blue", anumber: 2 }], { model_parameter: 'model parameter' });
 645    equal(col.length, 2);
 646    col.each(function(model) {
 647      equal(model.model_parameter, 'model parameter');
 648    });
 649  });
 650
 651  test("trigger custom events on models", 1, function() {
 652    var fired = null;
 653    a.on("custom", function() { fired = true; });
 654    a.trigger("custom");
 655    equal(fired, true);
 656  });
 657
 658  test("add does not alter arguments", 2, function(){
 659    var attrs = {};
 660    var models = [attrs];
 661    new Backbone.Collection().add(models);
 662    equal(models.length, 1);
 663    ok(attrs === models[0]);
 664  });
 665
 666  test("#714: access `model.collection` in a brand new model.", 2, function() {
 667    var collection = new Backbone.Collection;
 668    collection.url = '/test';
 669    var Model = Backbone.Model.extend({
 670      set: function(attrs) {
 671        equal(attrs.prop, 'value');
 672        equal(this.collection, collection);
 673        return this;
 674      }
 675    });
 676    collection.model = Model;
 677    collection.create({prop: 'value'});
 678  });
 679
 680  test("#574, remove its own reference to the .models array.", 2, function() {
 681    var col = new Backbone.Collection([
 682      {id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}
 683    ]);
 684    equal(col.length, 6);
 685    col.remove(col.models);
 686    equal(col.length, 0);
 687  });
 688
 689  test("#861, adding models to a collection which do not pass validation, with validate:true", function() {
 690      var Model = Backbone.Model.extend({
 691        validate: function(attrs) {
 692          if (attrs.id == 3) return "id can't be 3";
 693        }
 694      });
 695
 696      var Collection = Backbone.Collection.extend({
 697        model: Model
 698      });
 699
 700      var collection = new Collection;
 701      collection.on("error", function() { ok(true); });
 702
 703      collection.add([{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}], {validate:true});
 704      deepEqual(collection.pluck('id'), [1, 2, 4, 5, 6]);
 705  });
 706
 707  test("Invalid models are discarded with validate:true.", 5, function() {
 708    var collection = new Backbone.Collection;
 709    collection.on('test', function() { ok(true); });
 710    collection.model = Backbone.Model.extend({
 711      validate: function(attrs){ if (!attrs.valid) return 'invalid'; }
 712    });
 713    var model = new collection.model({id: 1, valid: true});
 714    collection.add([model, {id: 2}], {validate:true});
 715    model.trigger('test');
 716    ok(collection.get(model.cid));
 717    ok(collection.get(1));
 718    ok(!collection.get(2));
 719    equal(collection.length, 1);
 720  });
 721
 722  test("multiple copies of the same model", 3, function() {
 723    var col = new Backbone.Collection();
 724    var model = new Backbone.Model();
 725    col.add([model, model]);
 726    equal(col.length, 1);
 727    col.add([{id: 1}, {id: 1}]);
 728    equal(col.length, 2);
 729    equal(col.last().id, 1);
 730  });
 731
 732  test("#964 - collection.get return inconsistent", 2, function() {
 733    var c = new Backbone.Collection();
 734    ok(c.get(null) === undefined);
 735    ok(c.get() === undefined);
 736  });
 737
 738  test("#1112 - passing options.model sets collection.model", 2, function() {
 739    var Model = Backbone.Model.extend({});
 740    var c = new Backbone.Collection([{id: 1}], {model: Model});
 741    ok(c.model === Model);
 742    ok(c.at(0) instanceof Model);
 743  });
 744
 745  test("null and undefined are invalid ids.", 2, function() {
 746    var model = new Backbone.Model({id: 1});
 747    var collection = new Backbone.Collection([model]);
 748    model.set({id: null});
 749    ok(!collection.get('null'));
 750    model.set({id: 1});
 751    model.set({id: undefined});
 752    ok(!collection.get('undefined'));
 753  });
 754
 755  test("falsy comparator", 4, function(){
 756    var Col = Backbone.Collection.extend({
 757      comparator: function(model){ return model.id; }
 758    });
 759    var col = new Col();
 760    var colFalse = new Col(null, {comparator: false});
 761    var colNull = new Col(null, {comparator: null});
 762    var colUndefined = new Col(null, {comparator: undefined});
 763    ok(col.comparator);
 764    ok(!colFalse.comparator);
 765    ok(!colNull.comparator);
 766    ok(colUndefined.comparator);
 767  });
 768
 769  test("#1355 - `options` is passed to success callbacks", 2, function(){
 770    var m = new Backbone.Model({x:1});
 771    var col = new Backbone.Collection();
 772    var opts = {
 773      success: function(collection, resp, options){
 774        ok(options);
 775      }
 776    };
 777    col.sync = m.sync = function( method, collection, options ){
 778      options.success(collection, [], options);
 779    };
 780    col.fetch(opts);
 781    col.create(m, opts);
 782  });
 783
 784  test("#1412 - Trigger 'request' and 'sync' events.", 4, function() {
 785    var collection = new Backbone.Collection;
 786    collection.url = '/test';
 787    Backbone.ajax = function(settings){ settings.success(); };
 788
 789    collection.on('request', function(obj, xhr, options) {
 790      ok(obj === collection, "collection has correct 'request' event after fetching");
 791    });
 792    collection.on('sync', function(obj, response, options) {
 793      ok(obj === collection, "collection has correct 'sync' event after fetching");
 794    });
 795    collection.fetch();
 796    collection.off();
 797
 798    collection.on('request', function(obj, xhr, options) {
 799      ok(obj === collection.get(1), "collection has correct 'request' event after one of its models save");
 800    });
 801    collection.on('sync', function(obj, response, options) {
 802      ok(obj === collection.get(1), "collection has correct 'sync' event after one of its models save");
 803    });
 804    collection.create({id: 1});
 805    collection.off();
 806  });
 807
 808  test("#1447 - create with wait adds model.", 1, function() {
 809    var collection = new Backbone.Collection;
 810    var model = new Backbone.Model;
 811    model.sync = function(method, model, options){ options.success(); };
 812    collection.on('add', function(){ ok(true); });
 813    collection.create(model, {wait: true});
 814  });
 815
 816  test("#1448 - add sorts collection after merge.", 1, function() {
 817    var collection = new Backbone.Collection([
 818      {id: 1, x: 1},
 819      {id: 2, x: 2}
 820    ]);
 821    collection.comparator = function(model){ return model.get('x'); };
 822    collection.add({id: 1, x: 3}, {merge: true});
 823    deepEqual(collection.pluck('id'), [2, 1]);
 824  });
 825
 826  test("#1655 - groupBy can be used with a string argument.", 3, function() {
 827    var collection = new Backbone.Collection([{x: 1}, {x: 2}]);
 828    var grouped = collection.groupBy('x');
 829    strictEqual(_.keys(grouped).length, 2);
 830    strictEqual(grouped[1][0].get('x'), 1);
 831    strictEqual(grouped[2][0].get('x'), 2);
 832  });
 833
 834  test("#1655 - sortBy can be used with a string argument.", 1, function() {
 835    var collection = new Backbone.Collection([{x: 3}, {x: 1}, {x: 2}]);
 836    var values = _.map(collection.sortBy('x'), function(model) {
 837      return model.get('x');
 838    });
 839    deepEqual(values, [1, 2, 3]);
 840  });
 841
 842  test("#1604 - Removal during iteration.", 0, function() {
 843    var collection = new Backbone.Collection([{}, {}]);
 844    collection.on('add', function() {
 845      collection.at(0).destroy();
 846    });
 847    collection.add({}, {at: 0});
 848  });
 849
 850  test("#1638 - `sort` during `add` triggers correctly.", function() {
 851    var collection = new Backbone.Collection;
 852    collection.comparator = function(model) { return model.get('x'); };
 853    var added = [];
 854    collection.on('add', function(model) {
 855      model.set({x: 3});
 856      collection.sort();
 857      added.push(model.id);
 858    });
 859    collection.add([{id: 1, x: 1}, {id: 2, x: 2}]);
 860    deepEqual(added, [1, 2]);
 861  });
 862
 863  test("fetch parses models by default", 1, function() {
 864    var model = {};
 865    var Collection = Backbone.Collection.extend({
 866      url: 'test',
 867      model: Backbone.Model.extend({
 868        parse: function(resp) {
 869          strictEqual(resp, model);
 870        }
 871      })
 872    });
 873    new Collection().fetch();
 874    this.ajaxSettings.success([model]);
 875  });
 876
 877  test("`sort` shouldn't always fire on `add`", 1, function() {
 878    var c = new Backbone.Collection([{id: 1}, {id: 2}, {id: 3}], {
 879      comparator: 'id'
 880    });
 881    c.sort = function(){ ok(true); };
 882    c.add([]);
 883    c.add({id: 1});
 884    c.add([{id: 2}, {id: 3}]);
 885    c.add({id: 4});
 886  });
 887
 888  test("#1407 parse option on constructor parses collection and models", 2, function() {
 889    var model = {
 890      namespace : [{id: 1}, {id:2}]
 891    };
 892    var Collection = Backbone.Collection.extend({
 893      model: Backbone.Model.extend({
 894        parse: function(model) {
 895          model.name = 'test';
 896          return model;
 897        }
 898      }),
 899      parse: function(model) {
 900        return model.namespace;
 901      }
 902    });
 903    var c = new Collection(model, {parse:true});
 904
 905    equal(c.length, 2);
 906    equal(c.at(0).get('name'), 'test');
 907  });
 908
 909  test("#1407 parse option on reset parses collection and models", 2, function() {
 910    var model = {
 911      namespace : [{id: 1}, {id:2}]
 912    };
 913    var Collection = Backbone.Collection.extend({
 914      model: Backbone.Model.extend({
 915        parse: function(model) {
 916          model.name = 'test';
 917          return model;
 918        }
 919      }),
 920      parse: function(model) {
 921        return model.namespace;
 922      }
 923    });
 924    var c = new Collection();
 925        c.reset(model, {parse:true});
 926
 927    equal(c.length, 2);
 928    equal(c.at(0).get('name'), 'test');
 929  });
 930
 931
 932  test("Reset includes previous models in triggered event.", 1, function() {
 933    var model = new Backbone.Model();
 934    var collection = new Backbone.Collection([model])
 935    .on('reset', function(collection, options) {
 936      deepEqual(options.previousModels, [model]);
 937    });
 938    collection.reset([]);
 939  });
 940
 941  test("set", function() {
 942    var m1 = new Backbone.Model();
 943    var m2 = new Backbone.Model({id: 2});
 944    var m3 = new Backbone.Model();
 945    var c = new Backbone.Collection([m1, m2]);
 946
 947    // Test add/change/remove events
 948    c.on('add', function(model) {
 949      strictEqual(model, m3);
 950    });
 951    c.on('change', function(model) {
 952      strictEqual(model, m2);
 953    });
 954    c.on('remove', function(model) {
 955      strictEqual(model, m1);
 956    });
 957
 958    // remove: false doesn't remove any models
 959    c.set([], {remove: false});
 960    strictEqual(c.length, 2);
 961
 962    // add: false doesn't add any models
 963    c.set([m1, m2, m3], {add: false});
 964    strictEqual(c.length, 2);
 965
 966    // merge: false doesn't change any models
 967    c.set([m1, {id: 2, a: 1}], {merge: false});
 968    strictEqual(m2.get('a'), void 0);
 969
 970    // add: false, remove: false only merges existing models
 971    c.set([m1, {id: 2, a: 0}, m3, {id: 4}], {add: false, remove: false});
 972    strictEqual(c.length, 2);
 973    strictEqual(m2.get('a'), 0);
 974
 975    // default options add/remove/merge as appropriate
 976    c.set([{id: 2, a: 1}, m3]);
 977    strictEqual(c.length, 2);
 978    strictEqual(m2.get('a'), 1);
 979
 980    // Test removing models not passing an argument
 981    c.off('remove').on('remove', function(model) {
 982      ok(model === m2 || model === m3);
 983    });
 984    c.set([]);
 985    strictEqual(c.length, 0);
 986  });
 987
 988  test("set with only cids", 3, function() {
 989    var m1 = new Backbone.Model;
 990    var m2 = new Backbone.Model;
 991    var c = new Backbone.Collection;
 992    c.set([m1, m2]);
 993    equal(c.length, 2);
 994    c.set([m1]);
 995    equal(c.length, 1);
 996    c.set([m1, m1, m1, m2, m2], {remove: false});
 997    equal(c.length, 2);
 998  });
 999
1000  test("set with only idAttribute", 3, function() {
1001    var m1 = { _id: 1 };
1002    var m2 = { _id: 2 };
1003    var col = Backbone.Collection.extend({
1004      model: Backbone.Model.extend({
1005        idAttribute: '_id'
1006      })
1007    });
1008    var c = new col;
1009    c.set([m1, m2]);
1010    equal(c.length, 2);
1011    c.set([m1]);
1012    equal(c.length, 1);
1013    c.set([m1, m1, m1, m2, m2], {remove: false});
1014    equal(c.length, 2);
1015  });
1016
1017  test("set + merge with default values defined", function() {
1018    var Model = Backbone.Model.extend({
1019      defaults: {
1020        key: 'value'
1021      }
1022    });
1023    var m = new Model({id: 1});
1024    var col = new Backbone.Collection([m], {model: Model});
1025    equal(col.first().get('key'), 'value');
1026
1027    col.set({id: 1, key: 'other'});
1028    equal(col.first().get('key'), 'other');
1029
1030    col.set({id: 1, other: 'value'});
1031    equal(col.first().get('key'), 'other');
1032    equal(col.length, 1);
1033  });
1034
1035  test('merge without mutation', function () {
1036    var Model = Backbone.Model.extend({
1037      initialize: function (attrs, options) {
1038        if (attrs.child) {
1039          this.set('child', new Model(attrs.child, options), options);
1040        }
1041      }
1042    });
1043    var Collection = Backbone.Collection.extend({model: Model});
1044    var data = [{id: 1, child: {id: 2}}];
1045    var collection = new Collection(data);
1046    equal(collection.first().id, 1);
1047    collection.set(data);
1048    equal(collection.first().id, 1);
1049    collection.set([{id: 2, child: {id: 2}}].concat(data));
1050    deepEqual(collection.pluck('id'), [2, 1]);
1051  });
1052
1053  test("`set` and model level `parse`", function() {
1054    var Model = Backbone.Model.extend({});
1055    var Collection = Backbone.Collection.extend({
1056      model: Model,
1057      parse: function (res) { return _.pluck(res.models, 'model'); }
1058    });
1059    var model = new Model({id: 1});
1060    var collection = new Collection(model);
1061    collection.set({models: [
1062      {model: {id: 1}},
1063      {model: {id: 2}}
1064    ]}, {parse: true});
1065    equal(collection.first(), model);
1066  });
1067
1068  test("`set` data is only parsed once", function() {
1069    var collection = new Backbone.Collection();
1070    collection.model = Backbone.Model.extend({
1071      parse: function (data) {
1072        equal(data.parsed, void 0);
1073        data.parsed = true;
1074        return data;
1075      }
1076    });
1077    collection.set({}, {parse: true});
1078  });
1079
1080  test('`set` matches input order in the absence of a comparator', function () {
1081    var one = new Backbone.Model({id: 1});
1082    var two = new Backbone.Model({id: 2});
1083    var three = new Backbone.Model({id: 3});
1084    var collection = new Backbone.Collection([one, two, three]);
1085    collection.set([{id: 3}, {id: 2}, {id: 1}]);
1086    deepEqual(collection.models, [three, two, one]);
1087    collection.set([{id: 1}, {id: 2}]);
1088    deepEqual(collection.models, [one, two]);
1089    collection.set([two, three, one]);
1090    deepEqual(collection.models, [two, three, one]);
1091    collection.set([{id: 1}, {id: 2}], {remove: false});
1092    deepEqual(collection.models, [two, three, one]);
1093    collection.set([{id: 1}, {id: 2}, {id: 3}], {merge: false});
1094    deepEqual(collection.models, [one, two, three]);
1095    collection.set([three, two, one, {id: 4}], {add: false});
1096    deepEqual(collection.models, [one, two, three]);
1097  });
1098
1099  test("#1894 - Push should not trigger a sort", 0, function() {
1100    var Collection = Backbone.Collection.extend({
1101      comparator: 'id',
1102      sort: function() {
1103        ok(false);
1104      }
1105    });
1106    new Collection().push({id: 1});
1107  });
1108
1109  test("#2428 - push duplicate models, return the correct one", 1, function() {
1110    var col = new Backbone.Collection;
1111    var model1 = col.push({id: 101});
1112    var model2 = col.push({id: 101})
1113    ok(model2.cid == model1.cid);
1114  });
1115
1116  test("`set` with non-normal id", function() {
1117    var Collection = Backbone.Collection.extend({
1118      model: Backbone.Model.extend({idAttribute: '_id'})
1119    });
1120    var collection = new Collection({_id: 1});
1121    collection.set([{_id: 1, a: 1}], {add: false});
1122    equal(collection.first().get('a'), 1);
1123  });
1124
1125  test("#1894 - `sort` can optionally be turned off", 0, function() {
1126    var Collection = Backbone.Collection.extend({
1127      comparator: 'id',
1128      sort: function() { ok(true); }
1129    });
1130    new Collection().add({id: 1}, {sort: false});
1131  });
1132
1133  test("#1915 - `parse` data in the right order in `set`", function() {
1134    var collection = new (Backbone.Collection.extend({
1135      parse: function (data) {
1136        strictEqual(data.status, 'ok');
1137        return data.data;
1138      }
1139    }));
1140    var res = {status: 'ok', data:[{id: 1}]};
1141    collection.set(res, {parse: true});
1142  });
1143
1144  asyncTest("#1939 - `parse` is passed `options`", 1, function () {
1145    var collection = new (Backbone.Collection.extend({
1146      url: '/',
1147      parse: function (data, options) {
1148        strictEqual(options.xhr.someHeader, 'headerValue');
1149        return data;
1150      }
1151    }));
1152    var ajax = Backbone.ajax;
1153    Backbone.ajax = function (params) {
1154      _.defer(params.success);
1155      return {someHeader: 'headerValue'};
1156    };
1157    collection.fetch({
1158      success: function () { start(); }
1159    });
1160    Backbone.ajax = ajax;
1161  });
1162
1163  test("`add` only `sort`s when necessary", 2, function () {
1164    var collection = new (Backbone.Collection.extend({
1165      comparator: 'a'
1166    }))([{id: 1}, {id: 2}, {id: 3}]);
1167    collection.on('sort', function () { ok(true); });
1168    collection.add({id: 4}); // do sort, new model
1169    collection.add({id: 1, a: 1}, {merge: true}); // do sort, comparator change
1170    collection.add({id: 1, b: 1}, {merge: true}); // don't sort, no comparator change
1171    collection.add({id: 1, a: 1}, {merge: true}); // don't sort, no comparator change
1172    collection.add(collection.models); // don't sort, nothing new
1173    collection.add(collection.models, {merge: true}); // don't sort
1174  });
1175
1176  test("`add` only `sort`s when necessary with comparator function", 3, function () {
1177    var collection = new (Backbone.Collection.extend({
1178      comparator: function(a, b) {
1179        return a.get('a') > b.get('a') ? 1 : (a.get('a') < b.get('a') ? -1 : 0);
1180      }
1181    }))([{id: 1}, {id: 2}, {id: 3}]);
1182    collection.on('sort', function () { ok(true); });
1183    collection.add({id: 4}); // do sort, new model
1184    collection.add({id: 1, a: 1}, {merge: true}); // do sort, model change
1185    collection.add({id: 1, b: 1}, {merge: true}); // do sort, model change
1186    collection.add({id: 1, a: 1}, {merge: true}); // don't sort, no model change
1187    collection.add(collection.models); // don't sort, nothing new
1188    collection.add(collection.models, {merge: true}); // don't sort
1189  });
1190
1191  test("Attach options to collection.", 2, function() {
1192    var model = new Backbone.Model;
1193    var comparator = function(){};
1194
1195    var collection = new Backbone.Collection([], {
1196      model: model,
1197      comparator: comparator
1198    });
1199
1200    ok(collection.model === model);
1201    ok(collection.comparator === comparator);
1202  });
1203
1204  test("`add` overrides `set` flags", function () {
1205    var collection = new Backbone.Collection();
1206    collection.once('add', function (model, collection, options) {
1207      collection.add({id: 2}, options);
1208    });
1209    collection.set({id: 1});
1210    equal(collection.length, 2);
1211  });
1212
1213  test("#2606 - Collection#create, success arguments", 1, function() {
1214    var collection = new Backbone.Collection;
1215    collection.url = 'test';
1216    collection.create({}, {
1217      success: function(model, resp, options) {
1218        strictEqual(resp, 'response');
1219      }
1220    });
1221    this.ajaxSettings.success('response');
1222  });
1223
1224  test("#2612 - nested `parse` works with `Collection#set`", function() {
1225
1226    var Job = Backbone.Model.extend({
1227      constructor: function() {
1228        this.items = new Items();
1229        Backbone.Model.apply(this, arguments);
1230      },
1231      parse: function(attrs) {
1232        this.items.set(attrs.items, {parse: true});
1233        return _.omit(attrs, 'items');
1234      }
1235    });
1236
1237    var Item = Backbone.Model.extend({
1238      constructor: function() {
1239        this.subItems = new Backbone.Collection();
1240        Backbone.Model.apply(this, arguments);
1241      },
1242      parse: function(attrs) {
1243        this.subItems.set(attrs.subItems, {parse: true});
1244        return _.omit(attrs, 'subItems');
1245      }
1246    });
1247
1248    var Items = Backbone.Collection.extend({
1249      model: Item
1250    });
1251
1252    var data = {
1253      name: 'JobName',
1254      id: 1,
1255      items: [{
1256        id: 1,
1257        name: 'Sub1',
1258        subItems: [
1259          {id: 1, subName: 'One'},
1260          {id: 2, subName: 'Two'}
1261        ]
1262      }, {
1263        id: 2,
1264        name: 'Sub2',
1265        subItems: [
1266          {id: 3, subName: 'Three'},
1267          {id: 4, subName: 'Four'}
1268        ]
1269      }]
1270    };
1271
1272    var newData = {
1273      name: 'NewJobName',
1274      id: 1,
1275      items: [{
1276        id: 1,
1277        name: 'NewSub1',
1278        subItems: [
1279          {id: 1,subName: 'NewOne'},
1280          {id: 2,subName: 'NewTwo'}
1281        ]
1282      }, {
1283        id: 2,
1284        name: 'NewSub2',
1285        subItems: [
1286          {id: 3,subName: 'NewThree'},
1287          {id: 4,subName: 'NewFour'}
1288        ]
1289      }]
1290    };
1291
1292    var job = new Job(data, {parse: true});
1293    equal(job.get('name'), 'JobName');
1294    equal(job.items.at(0).get('name'), 'Sub1');
1295    equal(job.items.length, 2);
1296    equal(job.items.get(1).subItems.get(1).get('subName'), 'One');
1297    equal(job.items.get(2).subItems.get(3).get('subName'), 'Three');
1298    job.set(job.parse(newData, {parse: true}));
1299    equal(job.get('name'), 'NewJobName');
1300    equal(job.items.at(0).get('name'), 'NewSub1');
1301    equal(job.items.length, 2);
1302    equal(job.items.get(1).subItems.get(1).get('subName'), 'NewOne');
1303    equal(job.items.get(2).subItems.get(3).get('subName'), 'NewThree');
1304  });
1305
1306  test('_addReference binds all collection events & adds to the lookup hashes', 9, function() {
1307
1308    var calls = {add: 0, remove: 0};
1309
1310    var Collection = Backbone.Collection.extend({
1311
1312      _addReference: function(model) {
1313        Backbone.Collection.prototype._addReference.apply(this, arguments);
1314        calls.add++;
1315        equal(model, this._byId[model.id]);
1316        equal(model, this._byId[model.cid]);
1317        equal(model._events.all.length, 1);
1318      },
1319
1320      _removeReference: function(model) {
1321        Backbone.Collection.prototype._removeReference.apply(this, arguments);
1322        calls.remove++;
1323        equal(this._byId[model.id], void 0);
1324        equal(this._byId[model.cid], void 0);
1325        equal(model.collection, void 0);
1326        equal(model._events.all, void 0);
1327      }
1328
1329    });
1330
1331    var collection = new Collection();
1332    var model = collection.add({id: 1});
1333    collection.remove(model);
1334
1335    equal(calls.add, 1);
1336    equal(calls.remove, 1);
1337
1338  });
1339
1340  test('Do not allow duplicate models to be `add`ed or `set`', function() {
1341    var c = new Backbone.Collection();
1342
1343    c.add([{id: 1}, {id: 1}]);
1344    equal(c.length, 1);
1345    equal(c.models.length, 1);
1346
1347    c.set([{id: 1}, {id: 1}]);
1348    equal(c.length, 1);
1349    equal(c.models.length, 1);
1350  });
1351
1352  test('#3020: #set with {add: false} should not throw.', 2, function() {
1353    var collection = new Backbone.Collection;
1354    collection.set([{id: 1}], {add: false});
1355    strictEqual(collection.length, 0);
1356    strictEqual(collection.models.length, 0);
1357  });
1358
1359  test("create with wait, model instance, #3028", 1, function() {
1360    var collection = new Backbone.Collection();
1361    var model = new Backbone.Model({id: 1});
1362    model.sync = function(){
1363      equal(this.collection, collection);
1364    };
1365    collection.create(model, {wait: true});
1366  });
1367
1368})();