PageRenderTime 922ms CodeModel.GetById 82ms app.highlight 677ms RepoModel.GetById 97ms app.codeStats 1ms

/test/collection.js

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