PageRenderTime 4ms CodeModel.GetById 161ms app.highlight 164ms RepoModel.GetById 140ms app.codeStats 1ms

/static/backbone/test/collection.js

https://github.com/weblancer23/Final-Project
JavaScript | 432 lines | 387 code | 44 blank | 1 comment | 19 complexity | 5b66fb7fb68cedfde5ccd0a43920122e MD5 | raw file
  1$(document).ready(function() {
  2
  3  module("Backbone.Collection");
  4
  5  window.lastRequest = null;
  6
  7  Backbone.sync = function() {
  8    lastRequest = _.toArray(arguments);
  9  };
 10
 11  var a         = new Backbone.Model({id: 3, label: 'a'});
 12  var b         = new Backbone.Model({id: 2, label: 'b'});
 13  var c         = new Backbone.Model({id: 1, label: 'c'});
 14  var d         = new Backbone.Model({id: 0, label: 'd'});
 15  var e         = null;
 16  var col       = new Backbone.Collection([a,b,c,d]);
 17  var otherCol  = new Backbone.Collection();
 18
 19  test("Collection: new and sort", function() {
 20    equals(col.first(), a, "a should be first");
 21    equals(col.last(), d, "d should be last");
 22    col.comparator = function(model) { return model.id; };
 23    col.sort();
 24    equals(col.first(), d, "d should be first");
 25    equals(col.last(), a, "a should be last");
 26    equals(col.length, 4);
 27  });
 28
 29  test("Collection: get, getByCid", function() {
 30    equals(col.get(0), d);
 31    equals(col.get(2), b);
 32    equals(col.getByCid(col.first().cid), col.first());
 33  });
 34
 35  test("Collection: get with non-default ids", function() {
 36    var col = new Backbone.Collection();
 37    var MongoModel = Backbone.Model.extend({
 38      idAttribute: '_id'
 39    });
 40    var model = new MongoModel({_id: 100});
 41    col.add(model);
 42    equals(col.get(100), model);
 43    model.set({_id: 101});
 44    equals(col.get(101), model);
 45  });
 46
 47  test("Collection: add model with attributes modified by set", function() {
 48    var CustomSetModel = Backbone.Model.extend({
 49      defaults: {
 50        number_as_string: null //presence of defaults forces extend
 51      },
 52
 53      validate: function (attributes) {
 54        if (!_.isString(attributes.num_as_string)) {
 55          return 'fail';
 56        }
 57      },
 58
 59      set: function (attributes, options) {
 60        if (attributes.num_as_string) {
 61          attributes.num_as_string = attributes.num_as_string.toString();
 62        }
 63        Backbone.Model.prototype.set.call(this, attributes, options);
 64      }
 65    });
 66
 67    var CustomSetCollection = Backbone.Collection.extend({
 68      model: CustomSetModel
 69    });
 70    var col = new CustomSetCollection([{ num_as_string: 2 }]);
 71    equals(col.length, 1);
 72  });
 73
 74  test("Collection: update index when id changes", function() {
 75    var col = new Backbone.Collection();
 76    col.add([
 77      {id : 0, name : 'one'},
 78      {id : 1, name : 'two'}
 79    ]);
 80    var one = col.get(0);
 81    equals(one.get('name'), 'one');
 82    one.set({id : 101});
 83    equals(col.get(0), null);
 84    equals(col.get(101).get('name'), 'one');
 85  });
 86
 87  test("Collection: at", function() {
 88    equals(col.at(2), b);
 89  });
 90
 91  test("Collection: pluck", function() {
 92    equals(col.pluck('label').join(' '), 'd c b a');
 93  });
 94
 95  test("Collection: add", function() {
 96    var added = opts = secondAdded = null;
 97    e = new Backbone.Model({id: 10, label : 'e'});
 98    otherCol.add(e);
 99    otherCol.bind('add', function() {
100      secondAdded = true;
101    });
102    col.bind('add', function(model, collection, options){
103      added = model.get('label');
104      opts = options;
105    });
106    col.add(e, {amazing: true});
107    equals(added, 'e');
108    equals(col.length, 5);
109    equals(col.last(), e);
110    equals(otherCol.length, 1);
111    equals(secondAdded, null);
112    ok(opts.amazing);
113
114    var f = new Backbone.Model({id: 20, label : 'f'});
115    var g = new Backbone.Model({id: 21, label : 'g'});
116    var h = new Backbone.Model({id: 22, label : 'h'});
117    var atCol = new Backbone.Collection([f, g, h]);
118    equals(atCol.length, 3);
119    atCol.add(e, {at: 1});
120    equals(atCol.length, 4);
121    equals(atCol.at(1), e);
122    equals(atCol.last(), h);
123  });
124
125  test("Collection: add multiple models", function() {
126    var col = new Backbone.Collection([{at: 0}, {at: 1}, {at: 9}]);
127    col.add([{at: 2}, {at: 3}, {at: 4}, {at: 5}, {at: 6}, {at: 7}, {at: 8}], {at: 2});
128    for (var i = 0; i <= 5; i++) {
129      equals(col.at(i).get('at'), i);
130    }
131  });
132
133  test("Collection: add model to collection and verify index updates", function() {
134    var f = new Backbone.Model({id: 20, label : 'f'});
135    var g = new Backbone.Model({id: 21, label : 'g'});
136    var h = new Backbone.Model({id: 22, label : 'h'});
137    var col = new Backbone.Collection();
138
139    var counts = [];
140
141    col.bind('add', function(model, collection, options) {
142      counts.push(options.index);
143    });
144    col.add(f);
145    col.add(g);
146    col.add(h);
147    ok(_.isEqual(counts, [0,1,2]));
148  });
149
150  test("Collection: add model to collection twice", function() {
151    try {
152      // no id, same cid
153      var a2 = new Backbone.Model({label: a.label});
154      a2.cid = a.cid;
155      col.add(a2);
156      ok(false, "duplicate; expected add to fail");
157    } catch (e) {
158      equals(e.message, "Can't add the same model to a set twice,3");
159    }
160  });
161
162  test("Collection: add model to multiple collections", function() {
163    var counter = 0;
164    var e = new Backbone.Model({id: 10, label : 'e'});
165    e.bind('add', function(model, collection) {
166      counter++;
167      equals(e, model);
168      if (counter > 1) {
169        equals(collection, colF);
170      } else {
171        equals(collection, colE);
172      }
173    });
174    var colE = new Backbone.Collection([]);
175    colE.bind('add', function(model, collection) {
176      equals(e, model);
177      equals(colE, collection);
178    });
179    var colF = new Backbone.Collection([]);
180    colF.bind('add', function(model, collection) {
181      equals(e, model);
182      equals(colF, collection);
183    });
184    colE.add(e);
185    equals(e.collection, colE);
186    colF.add(e);
187    equals(e.collection, colE);
188  });
189
190  test("Collection: add model with parse", function() {
191    var Model = Backbone.Model.extend({
192      parse: function(obj) {
193        obj.value += 1;
194        return obj;
195      }
196    });
197
198    var Col = Backbone.Collection.extend({model: Model});
199    var col = new Col;
200    col.add({value: 1}, {parse: true});
201    equals(col.at(0).get('value'), 2);
202  });
203
204  test("Collection: remove", function() {
205    var removed = otherRemoved = null;
206    col.bind('remove', function(model){ removed = model.get('label'); });
207    otherCol.bind('remove', function(){ otherRemoved = true; });
208    col.remove(e);
209    equals(removed, 'e');
210    equals(col.length, 4);
211    equals(col.first(), d);
212    equals(otherRemoved, null);
213  });
214
215  test("Collection: remove should return correct index events", function() {
216    var f = new Backbone.Model({id: 20, label : 'f'});
217    var g = new Backbone.Model({id: 21, label : 'g'});
218    var h = new Backbone.Model({id: 22, label : 'h'});
219    var col = new Backbone.Collection([f,g,h]);
220
221    var counts = [];
222
223    col.bind('remove', function(model, collection, options) {
224      counts.push(options.index);
225    });
226    col.remove(h);
227    col.remove(g);
228    col.remove(f);
229    ok(_.isEqual(counts, [2,1,0]));
230  });
231
232  test("Collection: events are unbound on remove", function() {
233    var counter = 0;
234    var dj = new Backbone.Model();
235    var emcees = new Backbone.Collection([dj]);
236    emcees.bind('change', function(){ counter++; });
237    dj.set({name : 'Kool'});
238    equals(counter, 1);
239    emcees.reset([]);
240    equals(dj.collection, undefined);
241    dj.set({name : 'Shadow'});
242    equals(counter, 1);
243  });
244
245  test("Collection: remove in multiple collections", function() {
246    var modelData = {
247      id : 5,
248      title : 'Othello'
249    };
250    var passed = false;
251    var e = new Backbone.Model(modelData);
252    var f = new Backbone.Model(modelData);
253    f.bind('remove', function() {
254      passed = true;
255    });
256    var colE = new Backbone.Collection([e]);
257    var colF = new Backbone.Collection([f]);
258    ok(e != f);
259    ok(colE.length == 1);
260    ok(colF.length == 1);
261    colE.remove(e);
262    equals(passed, false);
263    ok(colE.length == 0);
264    colF.remove(e);
265    ok(colF.length == 0);
266    equals(passed, true);
267  });
268
269  test("Collection: remove same model in multiple collection", function() {
270    var counter = 0;
271    var e = new Backbone.Model({id: 5, title: 'Othello'});
272    e.bind('remove', function(model, collection) {
273      counter++;
274      equals(e, model);
275      if (counter > 1) {
276        equals(collection, colE);
277      } else {
278        equals(collection, colF);
279      }
280    });
281    var colE = new Backbone.Collection([e]);
282    colE.bind('remove', function(model, collection) {
283      equals(e, model);
284      equals(colE, collection);
285    });
286    var colF = new Backbone.Collection([e]);
287    colF.bind('remove', function(model, collection) {
288      equals(e, model);
289      equals(colF, collection);
290    });
291    equals(colE, e.collection);
292    colF.remove(e);
293    ok(colF.length == 0);
294    ok(colE.length == 1);
295    equals(counter, 1);
296    equals(colE, e.collection);
297    colE.remove(e);
298    equals(null, e.collection);
299    ok(colE.length == 0);
300    equals(counter, 2);
301  });
302
303  test("Collection: model destroy removes from all collections", function() {
304    var e = new Backbone.Model({id: 5, title: 'Othello'});
305    e.sync = function(method, model, options) { options.success({}); };
306    var colE = new Backbone.Collection([e]);
307    var colF = new Backbone.Collection([e]);
308    e.destroy();
309    ok(colE.length == 0);
310    ok(colF.length == 0);
311    equals(null, e.collection);
312  });
313
314  test("Colllection: non-persisted model destroy removes from all collections", function() {
315    var e = new Backbone.Model({title: 'Othello'});
316    e.sync = function(method, model, options) { throw "should not be called"; };
317    var colE = new Backbone.Collection([e]);
318    var colF = new Backbone.Collection([e]);
319    e.destroy();
320    ok(colE.length == 0);
321    ok(colF.length == 0);
322    equals(null, e.collection);
323  });
324
325  test("Collection: fetch", function() {
326    col.fetch();
327    equals(lastRequest[0], 'read');
328    equals(lastRequest[1], col);
329    equals(lastRequest[2].parse, true);
330
331    col.fetch({parse: false});
332    equals(lastRequest[2].parse, false);
333  });
334
335  test("Collection: create", function() {
336    var model = col.create({label: 'f'});
337    equals(lastRequest[0], 'create');
338    equals(lastRequest[1], model);
339    equals(model.get('label'), 'f');
340    equals(model.collection, col);
341  });
342
343  test("Collection: create enforces validation", function() {
344    var ValidatingModel = Backbone.Model.extend({
345      validate: function(attrs) {
346        return "fail";
347      }
348    });
349    var ValidatingCollection = Backbone.Collection.extend({
350      model: ValidatingModel
351    });
352    var col = new ValidatingCollection();
353    equals(col.create({"foo":"bar"}),false);
354  });
355
356  test("Collection: a failing create runs the error callback", function() {
357    var ValidatingModel = Backbone.Model.extend({
358      validate: function(attrs) {
359        return "fail";
360      }
361    });
362    var ValidatingCollection = Backbone.Collection.extend({
363      model: ValidatingModel
364    });
365    var flag = false;
366    var callback = function(model, error) { flag = true; };
367    var col = new ValidatingCollection();
368    col.create({"foo":"bar"}, { error: callback });
369    equals(flag, true);
370  });
371
372  test("collection: initialize", function() {
373    var Collection = Backbone.Collection.extend({
374      initialize: function() {
375        this.one = 1;
376      }
377    });
378    var coll = new Collection;
379    equals(coll.one, 1);
380  });
381
382  test("Collection: toJSON", function() {
383    equals(JSON.stringify(col), '[{"id":0,"label":"d"},{"id":1,"label":"c"},{"id":2,"label":"b"},{"id":3,"label":"a"}]');
384  });
385
386  test("Collection: Underscore methods", function() {
387    equals(col.map(function(model){ return model.get('label'); }).join(' '), 'd c b a');
388    equals(col.any(function(model){ return model.id === 100; }), false);
389    equals(col.any(function(model){ return model.id === 0; }), true);
390    equals(col.indexOf(b), 2);
391    equals(col.size(), 4);
392    equals(col.rest().length, 3);
393    ok(!_.include(col.rest()), a);
394    ok(!_.include(col.rest()), d);
395    ok(!col.isEmpty());
396    ok(!_.include(col.without(d)), d);
397    equals(col.max(function(model){ return model.id; }).id, 3);
398    equals(col.min(function(model){ return model.id; }).id, 0);
399    same(col.chain()
400            .filter(function(o){ return o.id % 2 === 0; })
401            .map(function(o){ return o.id * 2; })
402            .value(),
403         [0, 4]);
404  });
405
406  test("Collection: reset", function() {
407    var resetCount = 0;
408    var models = col.models;
409    col.bind('reset', function() { resetCount += 1; });
410    col.reset([]);
411    equals(resetCount, 1);
412    equals(col.length, 0);
413    equals(col.last(), null);
414    col.reset(models);
415    equals(resetCount, 2);
416    equals(col.length, 4);
417    equals(col.last(), a);
418    col.reset(_.map(models, function(m){ return m.attributes; }));
419    equals(resetCount, 3);
420    equals(col.length, 4);
421    ok(col.last() !== a);
422    ok(_.isEqual(col.last().attributes, a.attributes));
423  });
424
425  test("Collection: trigger custom events on models", function() {
426    var fired = null;
427    a.bind("custom", function() { fired = true; });
428    a.trigger("custom");
429    equals(fired, true);
430  });
431
432});