PageRenderTime 1001ms CodeModel.GetById 161ms app.highlight 655ms RepoModel.GetById 170ms app.codeStats 0ms

/bower_components/backbone-amd/test/collection.js

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