PageRenderTime 684ms CodeModel.GetById 101ms app.highlight 459ms RepoModel.GetById 84ms app.codeStats 1ms

/test/collection.js

https://gitlab.com/mba811/backbone
JavaScript | 1457 lines | 1292 code | 157 blank | 8 comment | 14 complexity | 0ffe769dd7d3d1eb2d68ed983b9130c6 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 MongoModel = Backbone.Model.extend({idAttribute: '_id'});
  88    var model = new MongoModel({_id: 100});
  89    var col = new Backbone.Collection([model], {model: MongoModel});
  90    equal(col.get(100), model);
  91    equal(col.get(model.cid), model);
  92    equal(col.get(model), model);
  93    equal(col.get(101), void 0);
  94
  95    var col2 = new Backbone.Collection();
  96    col2.model = MongoModel;
  97    col2.add(model.attributes);
  98    equal(col2.get(model.clone()), col2.first());
  99  });
 100
 101  test('get with "undefined" id', function() {
 102    var collection = new Backbone.Collection([{id: 1}, {id: 'undefined'}]);
 103    equal(collection.get(1).id, 1);
 104  }),
 105
 106  test("update index when id changes", 4, function() {
 107    var col = new Backbone.Collection();
 108    col.add([
 109      {id : 0, name : 'one'},
 110      {id : 1, name : 'two'}
 111    ]);
 112    var one = col.get(0);
 113    equal(one.get('name'), 'one');
 114    col.on('change:name', function (model) { ok(this.get(model)); });
 115    one.set({name: 'dalmatians', id : 101});
 116    equal(col.get(0), null);
 117    equal(col.get(101).get('name'), 'dalmatians');
 118  });
 119
 120  test("at", 2, function() {
 121    equal(col.at(2), c);
 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("reset does not alter options by reference", 2, function() {
 652    var col = new Backbone.Collection([{id:1}]);
 653    var origOpts = {};
 654    col.on("reset", function(col, opts){
 655      equal(origOpts.previousModels, undefined);
 656      equal(opts.previousModels[0].id, 1);
 657    });
 658    col.reset([], origOpts);
 659  });
 660
 661  test("trigger custom events on models", 1, function() {
 662    var fired = null;
 663    a.on("custom", function() { fired = true; });
 664    a.trigger("custom");
 665    equal(fired, true);
 666  });
 667
 668  test("add does not alter arguments", 2, function(){
 669    var attrs = {};
 670    var models = [attrs];
 671    new Backbone.Collection().add(models);
 672    equal(models.length, 1);
 673    ok(attrs === models[0]);
 674  });
 675
 676  test("#714: access `model.collection` in a brand new model.", 2, function() {
 677    var collection = new Backbone.Collection;
 678    collection.url = '/test';
 679    var Model = Backbone.Model.extend({
 680      set: function(attrs) {
 681        equal(attrs.prop, 'value');
 682        equal(this.collection, collection);
 683        return this;
 684      }
 685    });
 686    collection.model = Model;
 687    collection.create({prop: 'value'});
 688  });
 689
 690  test("#574, remove its own reference to the .models array.", 2, function() {
 691    var col = new Backbone.Collection([
 692      {id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}
 693    ]);
 694    equal(col.length, 6);
 695    col.remove(col.models);
 696    equal(col.length, 0);
 697  });
 698
 699  test("#861, adding models to a collection which do not pass validation, with validate:true", function() {
 700      var Model = Backbone.Model.extend({
 701        validate: function(attrs) {
 702          if (attrs.id == 3) return "id can't be 3";
 703        }
 704      });
 705
 706      var Collection = Backbone.Collection.extend({
 707        model: Model
 708      });
 709
 710      var collection = new Collection;
 711      collection.on("error", function() { ok(true); });
 712
 713      collection.add([{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}], {validate:true});
 714      deepEqual(collection.pluck('id'), [1, 2, 4, 5, 6]);
 715  });
 716
 717  test("Invalid models are discarded with validate:true.", 5, function() {
 718    var collection = new Backbone.Collection;
 719    collection.on('test', function() { ok(true); });
 720    collection.model = Backbone.Model.extend({
 721      validate: function(attrs){ if (!attrs.valid) return 'invalid'; }
 722    });
 723    var model = new collection.model({id: 1, valid: true});
 724    collection.add([model, {id: 2}], {validate:true});
 725    model.trigger('test');
 726    ok(collection.get(model.cid));
 727    ok(collection.get(1));
 728    ok(!collection.get(2));
 729    equal(collection.length, 1);
 730  });
 731
 732  test("multiple copies of the same model", 3, function() {
 733    var col = new Backbone.Collection();
 734    var model = new Backbone.Model();
 735    col.add([model, model]);
 736    equal(col.length, 1);
 737    col.add([{id: 1}, {id: 1}]);
 738    equal(col.length, 2);
 739    equal(col.last().id, 1);
 740  });
 741
 742  test("#964 - collection.get return inconsistent", 2, function() {
 743    var c = new Backbone.Collection();
 744    ok(c.get(null) === undefined);
 745    ok(c.get() === undefined);
 746  });
 747
 748  test("#1112 - passing options.model sets collection.model", 2, function() {
 749    var Model = Backbone.Model.extend({});
 750    var c = new Backbone.Collection([{id: 1}], {model: Model});
 751    ok(c.model === Model);
 752    ok(c.at(0) instanceof Model);
 753  });
 754
 755  test("null and undefined are invalid ids.", 2, function() {
 756    var model = new Backbone.Model({id: 1});
 757    var collection = new Backbone.Collection([model]);
 758    model.set({id: null});
 759    ok(!collection.get('null'));
 760    model.set({id: 1});
 761    model.set({id: undefined});
 762    ok(!collection.get('undefined'));
 763  });
 764
 765  test("falsy comparator", 4, function(){
 766    var Col = Backbone.Collection.extend({
 767      comparator: function(model){ return model.id; }
 768    });
 769    var col = new Col();
 770    var colFalse = new Col(null, {comparator: false});
 771    var colNull = new Col(null, {comparator: null});
 772    var colUndefined = new Col(null, {comparator: undefined});
 773    ok(col.comparator);
 774    ok(!colFalse.comparator);
 775    ok(!colNull.comparator);
 776    ok(colUndefined.comparator);
 777  });
 778
 779  test("#1355 - `options` is passed to success callbacks", 2, function(){
 780    var m = new Backbone.Model({x:1});
 781    var col = new Backbone.Collection();
 782    var opts = {
 783      opts: true,
 784      success: function(collection, resp, options) {
 785        ok(options.opts);
 786      }
 787    };
 788    col.sync = m.sync = function( method, collection, options ){
 789      options.success({});
 790    };
 791    col.fetch(opts);
 792    col.create(m, opts);
 793  });
 794
 795  test("#1412 - Trigger 'request' and 'sync' events.", 4, function() {
 796    var collection = new Backbone.Collection;
 797    collection.url = '/test';
 798    Backbone.ajax = function(settings){ settings.success(); };
 799
 800    collection.on('request', function(obj, xhr, options) {
 801      ok(obj === collection, "collection has correct 'request' event after fetching");
 802    });
 803    collection.on('sync', function(obj, response, options) {
 804      ok(obj === collection, "collection has correct 'sync' event after fetching");
 805    });
 806    collection.fetch();
 807    collection.off();
 808
 809    collection.on('request', function(obj, xhr, options) {
 810      ok(obj === collection.get(1), "collection has correct 'request' event after one of its models save");
 811    });
 812    collection.on('sync', function(obj, response, options) {
 813      ok(obj === collection.get(1), "collection has correct 'sync' event after one of its models save");
 814    });
 815    collection.create({id: 1});
 816    collection.off();
 817  });
 818
 819  test("#1447 - create with wait adds model.", 1, function() {
 820    var collection = new Backbone.Collection;
 821    var model = new Backbone.Model;
 822    model.sync = function(method, model, options){ options.success(); };
 823    collection.on('add', function(){ ok(true); });
 824    collection.create(model, {wait: true});
 825  });
 826
 827  test("#1448 - add sorts collection after merge.", 1, function() {
 828    var collection = new Backbone.Collection([
 829      {id: 1, x: 1},
 830      {id: 2, x: 2}
 831    ]);
 832    collection.comparator = function(model){ return model.get('x'); };
 833    collection.add({id: 1, x: 3}, {merge: true});
 834    deepEqual(collection.pluck('id'), [2, 1]);
 835  });
 836
 837  test("#1655 - groupBy can be used with a string argument.", 3, function() {
 838    var collection = new Backbone.Collection([{x: 1}, {x: 2}]);
 839    var grouped = collection.groupBy('x');
 840    strictEqual(_.keys(grouped).length, 2);
 841    strictEqual(grouped[1][0].get('x'), 1);
 842    strictEqual(grouped[2][0].get('x'), 2);
 843  });
 844
 845  test("#1655 - sortBy can be used with a string argument.", 1, function() {
 846    var collection = new Backbone.Collection([{x: 3}, {x: 1}, {x: 2}]);
 847    var values = _.map(collection.sortBy('x'), function(model) {
 848      return model.get('x');
 849    });
 850    deepEqual(values, [1, 2, 3]);
 851  });
 852
 853  test("#1604 - Removal during iteration.", 0, function() {
 854    var collection = new Backbone.Collection([{}, {}]);
 855    collection.on('add', function() {
 856      collection.at(0).destroy();
 857    });
 858    collection.add({}, {at: 0});
 859  });
 860
 861  test("#1638 - `sort` during `add` triggers correctly.", function() {
 862    var collection = new Backbone.Collection;
 863    collection.comparator = function(model) { return model.get('x'); };
 864    var added = [];
 865    collection.on('add', function(model) {
 866      model.set({x: 3});
 867      collection.sort();
 868      added.push(model.id);
 869    });
 870    collection.add([{id: 1, x: 1}, {id: 2, x: 2}]);
 871    deepEqual(added, [1, 2]);
 872  });
 873
 874  test("fetch parses models by default", 1, function() {
 875    var model = {};
 876    var Collection = Backbone.Collection.extend({
 877      url: 'test',
 878      model: Backbone.Model.extend({
 879        parse: function(resp) {
 880          strictEqual(resp, model);
 881        }
 882      })
 883    });
 884    new Collection().fetch();
 885    this.ajaxSettings.success([model]);
 886  });
 887
 888  test("`sort` shouldn't always fire on `add`", 1, function() {
 889    var c = new Backbone.Collection([{id: 1}, {id: 2}, {id: 3}], {
 890      comparator: 'id'
 891    });
 892    c.sort = function(){ ok(true); };
 893    c.add([]);
 894    c.add({id: 1});
 895    c.add([{id: 2}, {id: 3}]);
 896    c.add({id: 4});
 897  });
 898
 899  test("#1407 parse option on constructor parses collection and models", 2, function() {
 900    var model = {
 901      namespace : [{id: 1}, {id:2}]
 902    };
 903    var Collection = Backbone.Collection.extend({
 904      model: Backbone.Model.extend({
 905        parse: function(model) {
 906          model.name = 'test';
 907          return model;
 908        }
 909      }),
 910      parse: function(model) {
 911        return model.namespace;
 912      }
 913    });
 914    var c = new Collection(model, {parse:true});
 915
 916    equal(c.length, 2);
 917    equal(c.at(0).get('name'), 'test');
 918  });
 919
 920  test("#1407 parse option on reset parses collection and models", 2, function() {
 921    var model = {
 922      namespace : [{id: 1}, {id:2}]
 923    };
 924    var Collection = Backbone.Collection.extend({
 925      model: Backbone.Model.extend({
 926        parse: function(model) {
 927          model.name = 'test';
 928          return model;
 929        }
 930      }),
 931      parse: function(model) {
 932        return model.namespace;
 933      }
 934    });
 935    var c = new Collection();
 936        c.reset(model, {parse:true});
 937
 938    equal(c.length, 2);
 939    equal(c.at(0).get('name'), 'test');
 940  });
 941
 942
 943  test("Reset includes previous models in triggered event.", 1, function() {
 944    var model = new Backbone.Model();
 945    var collection = new Backbone.Collection([model])
 946    .on('reset', function(collection, options) {
 947      deepEqual(options.previousModels, [model]);
 948    });
 949    collection.reset([]);
 950  });
 951
 952  test("set", function() {
 953    var m1 = new Backbone.Model();
 954    var m2 = new Backbone.Model({id: 2});
 955    var m3 = new Backbone.Model();
 956    var c = new Backbone.Collection([m1, m2]);
 957
 958    // Test add/change/remove events
 959    c.on('add', function(model) {
 960      strictEqual(model, m3);
 961    });
 962    c.on('change', function(model) {
 963      strictEqual(model, m2);
 964    });
 965    c.on('remove', function(model) {
 966      strictEqual(model, m1);
 967    });
 968
 969    // remove: false doesn't remove any models
 970    c.set([], {remove: false});
 971    strictEqual(c.length, 2);
 972
 973    // add: false doesn't add any models
 974    c.set([m1, m2, m3], {add: false});
 975    strictEqual(c.length, 2);
 976
 977    // merge: false doesn't change any models
 978    c.set([m1, {id: 2, a: 1}], {merge: false});
 979    strictEqual(m2.get('a'), void 0);
 980
 981    // add: false, remove: false only merges existing models
 982    c.set([m1, {id: 2, a: 0}, m3, {id: 4}], {add: false, remove: false});
 983    strictEqual(c.length, 2);
 984    strictEqual(m2.get('a'), 0);
 985
 986    // default options add/remove/merge as appropriate
 987    c.set([{id: 2, a: 1}, m3]);
 988    strictEqual(c.length, 2);
 989    strictEqual(m2.get('a'), 1);
 990
 991    // Test removing models not passing an argument
 992    c.off('remove').on('remove', function(model) {
 993      ok(model === m2 || model === m3);
 994    });
 995    c.set([]);
 996    strictEqual(c.length, 0);
 997  });
 998
 999  test("set with only cids", 3, function() {
1000    var m1 = new Backbone.Model;
1001    var m2 = new Backbone.Model;
1002    var c = new Backbone.Collection;
1003    c.set([m1, m2]);
1004    equal(c.length, 2);
1005    c.set([m1]);
1006    equal(c.length, 1);
1007    c.set([m1, m1, m1, m2, m2], {remove: false});
1008    equal(c.length, 2);
1009  });
1010
1011  test("set with only idAttribute", 3, function() {
1012    var m1 = { _id: 1 };
1013    var m2 = { _id: 2 };
1014    var col = Backbone.Collection.extend({
1015      model: Backbone.Model.extend({
1016        idAttribute: '_id'
1017      })
1018    });
1019    var c = new col;
1020    c.set([m1, m2]);
1021    equal(c.length, 2);
1022    c.set([m1]);
1023    equal(c.length, 1);
1024    c.set([m1, m1, m1, m2, m2], {remove: false});
1025    equal(c.length, 2);
1026  });
1027
1028  test("set + merge with default values defined", function() {
1029    var Model = Backbone.Model.extend({
1030      defaults: {
1031        key: 'value'
1032      }
1033    });
1034    var m = new Model({id: 1});
1035    var col = new Backbone.Collection([m], {model: Model});
1036    equal(col.first().get('key'), 'value');
1037
1038    col.set({id: 1, key: 'other'});
1039    equal(col.first().get('key'), 'other');
1040
1041    col.set({id: 1, other: 'value'});
1042    equal(col.first().get('key'), 'other');
1043    equal(col.length, 1);
1044  });
1045
1046  test('merge without mutation', function () {
1047    var Model = Backbone.Model.extend({
1048      initialize: function (attrs, options) {
1049        if (attrs.child) {
1050          this.set('child', new Model(attrs.child, options), options);
1051        }
1052      }
1053    });
1054    var Collection = Backbone.Collection.extend({model: Model});
1055    var data = [{id: 1, child: {id: 2}}];
1056    var collection = new Collection(data);
1057    equal(collection.first().id, 1);
1058    collection.set(data);
1059    equal(collection.first().id, 1);
1060    collection.set([{id: 2, child: {id: 2}}].concat(data));
1061    deepEqual(collection.pluck('id'), [2, 1]);
1062  });
1063
1064  test("`set` and model level `parse`", function() {
1065    var Model = Backbone.Model.extend({});
1066    var Collection = Backbone.Collection.extend({
1067      model: Model,
1068      parse: function (res) { return _.pluck(res.models, 'model'); }
1069    });
1070    var model = new Model({id: 1});
1071    var collection = new Collection(model);
1072    collection.set({models: [
1073      {model: {id: 1}},
1074      {model: {id: 2}}
1075    ]}, {parse: true});
1076    equal(collection.first(), model);
1077  });
1078
1079  test("`set` data is only parsed once", function() {
1080    var collection = new Backbone.Collection();
1081    collection.model = Backbone.Model.extend({
1082      parse: function (data) {
1083        equal(data.parsed, void 0);
1084        data.parsed = true;
1085        return data;
1086      }
1087    });
1088    collection.set({}, {parse: true});
1089  });
1090
1091  test('`set` matches input order in the absence of a comparator', function () {
1092    var one = new Backbone.Model({id: 1});
1093    var two = new Backbone.Model({id: 2});
1094    var three = new Backbone.Model({id: 3});
1095    var collection = new Backbone.Collection([one, two, three]);
1096    collection.set([{id: 3}, {id: 2}, {id: 1}]);
1097    deepEqual(collection.models, [three, two, one]);
1098    collection.set([{id: 1}, {id: 2}]);
1099    deepEqual(collection.models, [one, two]);
1100    collection.set([two, three, one]);
1101    deepEqual(collection.models, [two, three, one]);
1102    collection.set([{id: 1}, {id: 2}], {remove: false});
1103    deepEqual(collection.models, [two, three, one]);
1104    collection.set([{id: 1}, {id: 2}, {id: 3}], {merge: false});
1105    deepEqual(collection.models, [one, two, three]);
1106    collection.set([three, two, one, {id: 4}], {add: false});
1107    deepEqual(collection.models, [one, two, three]);
1108  });
1109
1110  test("#1894 - Push should not trigger a sort", 0, function() {
1111    var Collection = Backbone.Collection.extend({
1112      comparator: 'id',
1113      sort: function() {
1114        ok(false);
1115      }
1116    });
1117    new Collection().push({id: 1});
1118  });
1119
1120  test("#2428 - push duplicate models, return the correct one", 1, function() {
1121    var col = new Backbone.Collection;
1122    var model1 = col.push({id: 101});
1123    var model2 = col.push({id: 101})
1124    ok(model2.cid == model1.cid);
1125  });
1126
1127  test("`set` with non-normal id", function() {
1128    var Collection = Backbone.Collection.extend({
1129      model: Backbone.Model.extend({idAttribute: '_id'})
1130    });
1131    var collection = new Collection({_id: 1});
1132    collection.set([{_id: 1, a: 1}], {add: false});
1133    equal(collection.first().get('a'), 1);
1134  });
1135
1136  test("#1894 - `sort` can optionally be turned off", 0, function() {
1137    var Collection = Backbone.Collection.extend({
1138      comparator: 'id',
1139      sort: function() { ok(true); }
1140    });
1141    new Collection().add({id: 1}, {sort: false});
1142  });
1143
1144  test("#1915 - `parse` data in the right order in `set`", function() {
1145    var collection = new (Backbone.Collection.extend({
1146      parse: function (data) {
1147        strictEqual(data.status, 'ok');
1148        return data.data;
1149      }
1150    }));
1151    var res = {status: 'ok', data:[{id: 1}]};
1152    collection.set(res, {parse: true});
1153  });
1154
1155  asyncTest("#1939 - `parse` is passed `options`", 1, function () {
1156    var collection = new (Backbone.Collection.extend({
1157      url: '/',
1158      parse: function (data, options) {
1159        strictEqual(options.xhr.someHeader, 'headerValue');
1160        return data;
1161      }
1162    }));
1163    var ajax = Backbone.ajax;
1164    Backbone.ajax = function (params) {
1165      _.defer(params.success);
1166      return {someHeader: 'headerValue'};
1167    };
1168    collection.fetch({
1169      success: function () { start(); }
1170    });
1171    Backbone.ajax = ajax;
1172  });
1173
1174  test("`add` only `sort`s when necessary", 2, function () {
1175    var collection = new (Backbone.Collection.extend({
1176      comparator: 'a'
1177    }))([{id: 1}, {id: 2}, {id: 3}]);
1178    collection.on('sort', function () { ok(true); });
1179    collection.add({id: 4}); // do sort, new model
1180    collection.add({id: 1, a: 1}, {merge: true}); // do sort, comparator change
1181    collection.add({id: 1, b: 1}, {merge: true}); // don't sort, no comparator change
1182    collection.add({id: 1, a: 1}, {merge: true}); // don't sort, no comparator change
1183    collection.add(collection.models); // don't sort, nothing new
1184    collection.add(collection.models, {merge: true}); // don't sort
1185  });
1186
1187  test("`add` only `sort`s when necessary with comparator function", 3, function () {
1188    var collection = new (Backbone.Collection.extend({
1189      comparator: function(a, b) {
1190        return a.get('a') > b.get('a') ? 1 : (a.get('a') < b.get('a') ? -1 : 0);
1191      }
1192    }))([{id: 1}, {id: 2}, {id: 3}]);
1193    collection.on('sort', function () { ok(true); });
1194    collection.add({id: 4}); // do sort, new model
1195    collection.add({id: 1, a: 1}, {merge: true}); // do sort, model change
1196    collection.add({id: 1, b: 1}, {merge: true}); // do sort, model change
1197    collection.add({id: 1, a: 1}, {merge: true}); // don't sort, no model change
1198    collection.add(collection.models); // don't sort, nothing new
1199    collection.add(collection.models, {merge: true}); // don't sort
1200  });
1201
1202  test("Attach options to collection.", 2, function() {
1203    var Model = Backbone.Model;
1204    var comparator = function(){};
1205
1206    var collection = new Backbone.Collection([], {
1207      model: Model,
1208      comparator: comparator
1209    });
1210
1211    ok(collection.model === Model);
1212    ok(collection.comparator === comparator);
1213  });
1214
1215  test("`add` overrides `set` flags", function () {
1216    var collection = new Backbone.Collection();
1217    collection.once('add', function (model, collection, options) {
1218      collection.add({id: 2}, options);
1219    });
1220    collection.set({id: 1});
1221    equal(collection.length, 2);
1222  });
1223
1224  test("#2606 - Collection#create, success arguments", 1, function() {
1225    var collection = new Backbone.Collection;
1226    collection.url = 'test';
1227    collection.create({}, {
1228      success: function(model, resp, options) {
1229        strictEqual(resp, 'response');
1230      }
1231    });
1232    this.ajaxSettings.success('response');
1233  });
1234
1235  test("#2612 - nested `parse` works with `Collection#set`", function() {
1236
1237    var Job = Backbone.Model.extend({
1238      constructor: function() {
1239        this.items = new Items();
1240        Backbone.Model.apply(this, arguments);
1241      },
1242      parse: function(attrs) {
1243        this.items.set(attrs.items, {parse: true});
1244        return _.omit(attrs, 'items');
1245      }
1246    });
1247
1248    var Item = Backbone.Model.extend({
1249      constructor: function() {
1250        this.subItems = new Backbone.Collection();
1251        Backbone.Model.apply(this, arguments);
1252      },
1253      parse: function(attrs) {
1254        this.subItems.set(attrs.subItems, {parse: true});
1255        return _.omit(attrs, 'subItems');
1256      }
1257    });
1258
1259    var Items = Backbone.Collection.extend({
1260      model: Item
1261    });
1262
1263    var data = {
1264      name: 'JobName',
1265      id: 1,
1266      items: [{
1267        id: 1,
1268        name: 'Sub1',
1269        subItems: [
1270          {id: 1, subName: 'One'},
1271          {id: 2, subName: 'Two'}
1272        ]
1273      }, {
1274        id: 2,
1275        name: 'Sub2',
1276        subItems: [
1277          {id: 3, subName: 'Three'},
1278          {id: 4, subName: 'Four'}
1279        ]
1280      }]
1281    };
1282
1283    var newData = {
1284      name: 'NewJobName',
1285      id: 1,
1286      items: [{
1287        id: 1,
1288        name: 'NewSub1',
1289        subItems: [
1290          {id: 1,subName: 'NewOne'},
1291          {id: 2,subName: 'NewTwo'}
1292        ]
1293      }, {
1294        id: 2,
1295        name: 'NewSub2',
1296        subItems: [
1297          {id: 3,subName: 'NewThree'},
1298          {id: 4,subName: 'NewFour'}
1299        ]
1300      }]
1301    };
1302
1303    var job = new Job(data, {parse: true});
1304    equal(job.get('name'), 'JobName');
1305    equal(job.items.at(0).get('name'), 'Sub1');
1306    equal(job.items.length, 2);
1307    equal(job.items.get(1).subItems.get(1).get('subName'), 'One');
1308    equal(job.items.get(2).subItems.get(3).get('subName'), 'Three');
1309    job.set(job.parse(newData, {parse: true}));
1310    equal(job.get('name'), 'NewJobName');
1311    equal(job.items.at(0).get('name'), 'NewSub1');
1312    equal(job.items.length, 2);
1313    equal(job.items.get(1).subItems.get(1).get('subName'), 'NewOne');
1314    equal(job.items.get(2).subItems.get(3).get('subName'), 'NewThree');
1315  });
1316
1317  test('_addReference binds all collection events & adds to the lookup hashes', 9, function() {
1318
1319    var calls = {add: 0, remove: 0};
1320
1321    var Collection = Backbone.Collection.extend({
1322
1323      _addReference: function(model) {
1324        Backbone.Collection.prototype._addReference.apply(this, arguments);
1325        calls.add++;
1326        equal(model, this._byId[model.id]);
1327        equal(model, this._byId[model.cid]);
1328        equal(model._events.all.length, 1);
1329      },
1330
1331      _removeReference: function(model) {
1332        Backbone.Collection.prototype._removeReference.apply(this, arguments);
1333        calls.remove++;
1334        equal(this._byId[model.id], void 0);
1335        equal(this._byId[model.cid], void 0);
1336        equal(model.collection, void 0);
1337        equal(model._events.all, void 0);
1338      }
1339
1340    });
1341
1342    var collection = new Collection();
1343    var model = collection.add({id: 1});
1344    collection.remove(model);
1345
1346    equal(calls.add, 1);
1347    equal(calls.remove, 1);
1348
1349  });
1350
1351  test('Do not allow duplicate models to be `add`ed or `set`', function() {
1352    var c = new Backbone.Collection();
1353
1354    c.add([{id: 1}, {id: 1}]);
1355    equal(c.length, 1);
1356    equal(c.models.length, 1);
1357
1358    c.set([{id: 1}, {id: 1}]);
1359    equal(c.length, 1);
1360    equal(c.models.length, 1);
1361  });
1362
1363  test('#3020: #set with {add: false} should not throw.', 2, function() {
1364    var collection = new Backbone.Collection;
1365    collection.set([{id: 1}], {add: false});
1366    strictEqual(collection.length, 0);
1367    strictEqual(collection.models.length, 0);
1368  });
1369
1370  test("create with wait, model instance, #3028", 1, function() {
1371    var collection = new Backbone.Collection();
1372    var model = new Backbone.Model({id: 1});
1373    model.sync = function(){
1374      equal(this.collection, collection);
1375    };
1376    collection.create(model, {wait: true});
1377  });
1378
1379  test("modelId", function() {
1380    var Stooge = Backbone.Model.extend();
1381    var StoogeCollection = Backbone.Collection.extend({model: Stooge});
1382
1383    // Default to using `Collection::model::idAttribute`.
1384    equal(StoogeCollection.prototype.modelId({id: 1}), 1);
1385    Stooge.prototype.idAttribute = '_id';
1386    equal(StoogeCollection.prototype.modelId({_id: 1}), 1);
1387  });
1388
1389  test('Polymorphic models work with "simple" constructors', function () {
1390    var A = Backbone.Model.extend();
1391    var B = Backbone.Model.extend();
1392    var C = Backbone.Collection.extend({
1393      model: function (attrs) {
1394        return attrs.type === 'a' ? new A(attrs) : new B(attrs);
1395      }
1396    });
1397    var collection = new C([{id: 1, type: 'a'}, {id: 2, type: 'b'}]);
1398    equal(collection.length, 2);
1399    ok(collection.at(0) instanceof A);
1400    equal(collection.at(0).id, 1);
1401    ok(collection.at(1) instanceof B);
1402    equal(collection.at(1).id, 2);
1403  });
1404
1405  test('Polymorphic models work with "advanced" constructors', function () {
1406    var A = Backbone.Model.extend({idAttribute: '_id'});
1407    var B = Backbone.Model.extend({idAttribute: '_id'});
1408    var C = Backbone.Collection.extend({
1409      model: Backbone.Model.extend({
1410        constructor: function (attrs) {
1411          return attrs.type === 'a' ? new A(attrs) : new B(attrs);
1412        },
1413
1414        idAttribute: '_id'
1415      })
1416    });
1417    var collection = new C([{_id: 1, type: 'a'}, {_id: 2, type: 'b'}]);
1418    equal(collection.length, 2);
1419    ok(collection.at(0) instanceof A);
1420    equal(collection.at(0), collection.get(1));
1421    ok(collection.at(1) instanceof B);
1422    equal(collection.at(1), collection.get(2));
1423
1424    C = Backbone.Collection.extend({
1425      model: function (attrs) {
1426        return attrs.type === 'a' ? new A(attrs) : new B(attrs);
1427      },
1428
1429      modelId: function (attrs) {
1430        return attrs.type + '-' + attrs.id;
1431      }
1432    });
1433    collection = new C([{id: 1, type: 'a'}, {id: 1, type: 'b'}]);
1434    equal(collection.length, 2);
1435    ok(collection.at(0) instanceof A);
1436    equal(collection.at(0), collection.get('a-1'));
1437    ok(collection.at(1) instanceof B);
1438    equal(collection.at(1), collection.get('b-1'));
1439  });
1440
1441  test("#3039: adding at index fires with correct at", 3, function() {
1442    var col = new Backbone.Collection([{at: 0}, {at: 4}]);
1443    col.on('add', function(model, col, options) {
1444        equal(model.get('at'), options.index);
1445    });
1446    col.add([{at: 1}, {at: 2}, {at: 3}], {at: 1});
1447  });
1448
1449  test("#3039: index is not sent when at is not specified", 2, function() {
1450    var col = new Backbone.Collection([{at: 0}]);
1451    col.on('add', function(model, col, options) {
1452        equal(undefined, options.index);
1453    });
1454    col.add([{at: 1}, {at: 2}]);
1455  });
1456
1457})();