PageRenderTime 64ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/test/collection.js

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