PageRenderTime 189ms CodeModel.GetById 694ms app.highlight 776ms RepoModel.GetById 124ms app.codeStats 0ms

/test/collection.js

https://github.com/parkerproject/backbone
JavaScript | 406 lines | 365 code | 40 blank | 1 comment | 18 complexity | 7458c805096e5a310d5dfb67ffaaa07a 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 model to collection and verify index updates", function() {
126    var f = new Backbone.Model({id: 20, label : 'f'});
127    var g = new Backbone.Model({id: 21, label : 'g'});
128    var h = new Backbone.Model({id: 22, label : 'h'});
129    var col = new Backbone.Collection();
130    
131    var counts = [];
132     
133    col.bind('add', function(model, collection, options) {
134      counts.push(options.index);  
135    });
136    col.add(f); 
137    col.add(g); 
138    col.add(h); 
139    ok(_.isEqual(counts, [0,1,2]));
140  });
141
142  test("Collection: add model to collection twice", function() {
143    try {
144      // no id, same cid
145      var a2 = new Backbone.Model({label: a.label});
146      a2.cid = a.cid;
147      col.add(a2);
148      ok(false, "duplicate; expected add to fail");
149    } catch (e) {
150      equals(e.message, "Can't add the same model to a set twice,3");
151    }
152  });
153
154  test("Collection: add model to multiple collections", function() {
155    var counter = 0;
156    var e = new Backbone.Model({id: 10, label : 'e'});
157    e.bind('add', function(model, collection) {
158      counter++;
159      equals(e, model);
160      if (counter > 1) {
161        equals(collection, colF);
162      } else {
163        equals(collection, colE);
164      }
165    });
166    var colE = new Backbone.Collection([]);
167    colE.bind('add', function(model, collection) {
168      equals(e, model);
169      equals(colE, collection);
170    });
171    var colF = new Backbone.Collection([]);
172    colF.bind('add', function(model, collection) {
173      equals(e, model);
174      equals(colF, collection);
175    });
176    colE.add(e);
177    equals(e.collection, colE);
178    colF.add(e);
179    equals(e.collection, colE);
180  });
181
182  test("Collection: remove", function() {
183    var removed = otherRemoved = null;
184    col.bind('remove', function(model){ removed = model.get('label'); });
185    otherCol.bind('remove', function(){ otherRemoved = true; });
186    col.remove(e);
187    equals(removed, 'e');
188    equals(col.length, 4);
189    equals(col.first(), d);
190    equals(otherRemoved, null);
191  });
192
193  test("Collection: remove should return correct index events", function() {
194    var f = new Backbone.Model({id: 20, label : 'f'});
195    var g = new Backbone.Model({id: 21, label : 'g'});
196    var h = new Backbone.Model({id: 22, label : 'h'});
197    var col = new Backbone.Collection([f,g,h]);
198    
199    var counts = [];
200     
201    col.bind('remove', function(model, collection, options) {
202      counts.push(options.index);  
203    });
204    col.remove(h); 
205    col.remove(g); 
206    col.remove(f); 
207    ok(_.isEqual(counts, [2,1,0]));
208  });
209
210  test("Collection: events are unbound on remove", function() {
211    var counter = 0;
212    var dj = new Backbone.Model();
213    var emcees = new Backbone.Collection([dj]);
214    emcees.bind('change', function(){ counter++; });
215    dj.set({name : 'Kool'});
216    equals(counter, 1);
217    emcees.reset([]);
218    equals(dj.collection, undefined);
219    dj.set({name : 'Shadow'});
220    equals(counter, 1);
221  });
222
223  test("Collection: remove in multiple collections", function() {
224    var modelData = {
225      id : 5,
226      title : 'Othello'
227    };
228    var passed = false;
229    var e = new Backbone.Model(modelData);
230    var f = new Backbone.Model(modelData);
231    f.bind('remove', function() {
232      passed = true;
233    });
234    var colE = new Backbone.Collection([e]);
235    var colF = new Backbone.Collection([f]);
236    ok(e != f);
237    ok(colE.length == 1);
238    ok(colF.length == 1);
239    colE.remove(e);
240    equals(passed, false);
241    ok(colE.length == 0);
242    colF.remove(e);
243    ok(colF.length == 0);
244    equals(passed, true);
245  });
246
247  test("Collection: remove same model in multiple collection", function() {
248    var counter = 0;
249    var e = new Backbone.Model({id: 5, title: 'Othello'});
250    e.bind('remove', function(model, collection) {
251      counter++;
252      equals(e, model);
253      if (counter > 1) {
254        equals(collection, colE);
255      } else {
256        equals(collection, colF);
257      }
258    });
259    var colE = new Backbone.Collection([e]);
260    colE.bind('remove', function(model, collection) {
261      equals(e, model);
262      equals(colE, collection);
263    });
264    var colF = new Backbone.Collection([e]);
265    colF.bind('remove', function(model, collection) {
266      equals(e, model);
267      equals(colF, collection);
268    });
269    equals(colE, e.collection);
270    colF.remove(e);
271    ok(colF.length == 0);
272    ok(colE.length == 1);
273    equals(counter, 1);
274    equals(colE, e.collection);
275    colE.remove(e);
276    equals(null, e.collection);
277    ok(colE.length == 0);
278    equals(counter, 2);
279  });
280
281  test("Collection: model destroy removes from all collections", function() {
282    var e = new Backbone.Model({id: 5, title: 'Othello'});
283    e.sync = function(method, model, options) { options.success({}); };
284    var colE = new Backbone.Collection([e]);
285    var colF = new Backbone.Collection([e]);
286    e.destroy();
287    ok(colE.length == 0);
288    ok(colF.length == 0);
289    equals(null, e.collection);
290  });
291
292  test("Colllection: non-persisted model destroy removes from all collections", function() {
293    var e = new Backbone.Model({title: 'Othello'});
294    e.sync = function(method, model, options) { throw "should not be called"; };
295    var colE = new Backbone.Collection([e]);
296    var colF = new Backbone.Collection([e]);
297    e.destroy();
298    ok(colE.length == 0);
299    ok(colF.length == 0);
300    equals(null, e.collection);
301  });
302
303  test("Collection: fetch", function() {
304    col.fetch();
305    equals(lastRequest[0], 'read');
306    equals(lastRequest[1], col);
307  });
308
309  test("Collection: create", function() {
310    var model = col.create({label: 'f'});
311    equals(lastRequest[0], 'create');
312    equals(lastRequest[1], model);
313    equals(model.get('label'), 'f');
314    equals(model.collection, col);
315  });
316
317  test("Collection: create enforces validation", function() {
318    var ValidatingModel = Backbone.Model.extend({
319      validate: function(attrs) {
320        return "fail";
321      }
322    });
323    var ValidatingCollection = Backbone.Collection.extend({
324      model: ValidatingModel
325    });
326    var col = new ValidatingCollection();
327    equals(col.create({"foo":"bar"}),false);
328  });
329
330  test("Collection: a failing create runs the error callback", function() {
331    var ValidatingModel = Backbone.Model.extend({
332      validate: function(attrs) {
333        return "fail";
334      }
335    });
336    var ValidatingCollection = Backbone.Collection.extend({
337      model: ValidatingModel
338    });
339    var flag = false;
340    var callback = function(model, error) { flag = true; };
341    var col = new ValidatingCollection();
342    col.create({"foo":"bar"}, { error: callback });
343    equals(flag, true);
344  });
345
346  test("collection: initialize", function() {
347    var Collection = Backbone.Collection.extend({
348      initialize: function() {
349        this.one = 1;
350      }
351    });
352    var coll = new Collection;
353    equals(coll.one, 1);
354  });
355
356  test("Collection: toJSON", function() {
357    equals(JSON.stringify(col), '[{"id":0,"label":"d"},{"id":1,"label":"c"},{"id":2,"label":"b"},{"id":3,"label":"a"}]');
358  });
359
360  test("Collection: Underscore methods", function() {
361    equals(col.map(function(model){ return model.get('label'); }).join(' '), 'd c b a');
362    equals(col.any(function(model){ return model.id === 100; }), false);
363    equals(col.any(function(model){ return model.id === 0; }), true);
364    equals(col.indexOf(b), 2);
365    equals(col.size(), 4);
366    equals(col.rest().length, 3);
367    ok(!_.include(col.rest()), a);
368    ok(!_.include(col.rest()), d);
369    ok(!col.isEmpty());
370    ok(!_.include(col.without(d)), d);
371    equals(col.max(function(model){ return model.id; }).id, 3);
372    equals(col.min(function(model){ return model.id; }).id, 0);
373    same(col.chain()
374            .filter(function(o){ return o.id % 2 === 0; })
375            .map(function(o){ return o.id * 2; })
376            .value(),
377         [0, 4]);
378  });
379
380  test("Collection: reset", function() {
381    var resetCount = 0;
382    var models = col.models;
383    col.bind('reset', function() { resetCount += 1; });
384    col.reset([]);
385    equals(resetCount, 1);
386    equals(col.length, 0);
387    equals(col.last(), null);
388    col.reset(models);
389    equals(resetCount, 2);
390    equals(col.length, 4);
391    equals(col.last(), a);
392    col.reset(_.map(models, function(m){ return m.attributes; }));
393    equals(resetCount, 3);
394    equals(col.length, 4);
395    ok(col.last() !== a);
396    ok(_.isEqual(col.last().attributes, a.attributes));
397  });
398
399  test("Collection: trigger custom events on models", function() {
400    var fired = null;
401    a.bind("custom", function() { fired = true; });
402    a.trigger("custom");
403    equals(fired, true);
404  });
405
406});