PageRenderTime 90ms CodeModel.GetById 26ms RepoModel.GetById 14ms app.codeStats 0ms

/node_modules/ender/test/node_modules/backbone/test/model.js

http://github.com/projexsys/Jolt
JavaScript | 680 lines | 599 code | 77 blank | 4 comment | 12 complexity | 62f7ab2a8bf9e7399a483d553e2477d6 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-3.0, Apache-2.0, MIT, BSD-3-Clause
  1. $(document).ready(function() {
  2. // Variable to catch the last request.
  3. var lastRequest = null;
  4. // Variable to catch ajax params.
  5. var ajaxParams = null;
  6. var sync = Backbone.sync;
  7. var ajax = $.ajax;
  8. var urlRoot = null;
  9. module("Backbone.Model", {
  10. setup: function() {
  11. Backbone.sync = function() {
  12. lastRequest = _.toArray(arguments);
  13. sync.apply(this, arguments);
  14. };
  15. $.ajax = function(params) { ajaxParams = params; };
  16. urlRoot = Backbone.Model.prototype.urlRoot;
  17. Backbone.Model.prototype.urlRoot = '/';
  18. },
  19. teardown: function() {
  20. Backbone.sync = sync;
  21. $.ajax = ajax;
  22. Backbone.Model.prototype.urlRoot = urlRoot;
  23. }
  24. });
  25. var attrs = {
  26. id : '1-the-tempest',
  27. title : "The Tempest",
  28. author : "Bill Shakespeare",
  29. length : 123
  30. };
  31. var proxy = Backbone.Model.extend();
  32. var doc = new proxy(attrs);
  33. var klass = Backbone.Collection.extend({
  34. url : function() { return '/collection'; }
  35. });
  36. var collection = new klass();
  37. collection.add(doc);
  38. test("Model: initialize", function() {
  39. var Model = Backbone.Model.extend({
  40. initialize: function() {
  41. this.one = 1;
  42. equal(this.collection, collection);
  43. }
  44. });
  45. var model = new Model({}, {collection: collection});
  46. equal(model.one, 1);
  47. equal(model.collection, collection);
  48. });
  49. test("Model: initialize with attributes and options", function() {
  50. var Model = Backbone.Model.extend({
  51. initialize: function(attributes, options) {
  52. this.one = options.one;
  53. }
  54. });
  55. var model = new Model({}, {one: 1});
  56. equal(model.one, 1);
  57. });
  58. test("Model: initialize with parsed attributes", function() {
  59. var Model = Backbone.Model.extend({
  60. parse: function(obj) {
  61. obj.value += 1;
  62. return obj;
  63. }
  64. });
  65. var model = new Model({value: 1}, {parse: true});
  66. equal(model.get('value'), 2);
  67. });
  68. test("Model: url", function() {
  69. equal(doc.url(), '/collection/1-the-tempest');
  70. doc.collection.url = '/collection/';
  71. equal(doc.url(), '/collection/1-the-tempest');
  72. doc.collection = null;
  73. doc.urlRoot = null;
  74. raises(function() { doc.url(); });
  75. doc.collection = collection;
  76. });
  77. test("Model: url when using urlRoot, and uri encoding", function() {
  78. var Model = Backbone.Model.extend({
  79. urlRoot: '/collection'
  80. });
  81. var model = new Model();
  82. equal(model.url(), '/collection');
  83. model.set({id: '+1+'});
  84. equal(model.url(), '/collection/%2B1%2B');
  85. });
  86. test("Model: url when using urlRoot as a function to determine urlRoot at runtime", function() {
  87. var Model = Backbone.Model.extend({
  88. urlRoot: function() {
  89. return '/nested/' + this.get('parent_id') + '/collection';
  90. }
  91. });
  92. var model = new Model({parent_id: 1});
  93. equal(model.url(), '/nested/1/collection');
  94. model.set({id: 2});
  95. equal(model.url(), '/nested/1/collection/2');
  96. });
  97. test("Model: clone", function() {
  98. attrs = { 'foo': 1, 'bar': 2, 'baz': 3};
  99. a = new Backbone.Model(attrs);
  100. b = a.clone();
  101. equal(a.get('foo'), 1);
  102. equal(a.get('bar'), 2);
  103. equal(a.get('baz'), 3);
  104. equal(b.get('foo'), a.get('foo'), "Foo should be the same on the clone.");
  105. equal(b.get('bar'), a.get('bar'), "Bar should be the same on the clone.");
  106. equal(b.get('baz'), a.get('baz'), "Baz should be the same on the clone.");
  107. a.set({foo : 100});
  108. equal(a.get('foo'), 100);
  109. equal(b.get('foo'), 1, "Changing a parent attribute does not change the clone.");
  110. });
  111. test("Model: isNew", function() {
  112. attrs = { 'foo': 1, 'bar': 2, 'baz': 3};
  113. a = new Backbone.Model(attrs);
  114. ok(a.isNew(), "it should be new");
  115. attrs = { 'foo': 1, 'bar': 2, 'baz': 3, 'id': -5 };
  116. a = new Backbone.Model(attrs);
  117. ok(!a.isNew(), "any defined ID is legal, negative or positive");
  118. attrs = { 'foo': 1, 'bar': 2, 'baz': 3, 'id': 0 };
  119. a = new Backbone.Model(attrs);
  120. ok(!a.isNew(), "any defined ID is legal, including zero");
  121. ok( new Backbone.Model({ }).isNew(), "is true when there is no id");
  122. ok(!new Backbone.Model({ 'id': 2 }).isNew(), "is false for a positive integer");
  123. ok(!new Backbone.Model({ 'id': -5 }).isNew(), "is false for a negative integer");
  124. });
  125. test("Model: get", function() {
  126. equal(doc.get('title'), 'The Tempest');
  127. equal(doc.get('author'), 'Bill Shakespeare');
  128. });
  129. test("Model: escape", function() {
  130. equal(doc.escape('title'), 'The Tempest');
  131. doc.set({audience: 'Bill & Bob'});
  132. equal(doc.escape('audience'), 'Bill & Bob');
  133. doc.set({audience: 'Tim > Joan'});
  134. equal(doc.escape('audience'), 'Tim > Joan');
  135. doc.set({audience: 10101});
  136. equal(doc.escape('audience'), '10101');
  137. doc.unset('audience');
  138. equal(doc.escape('audience'), '');
  139. });
  140. test("Model: has", function() {
  141. attrs = {};
  142. a = new Backbone.Model(attrs);
  143. equal(a.has("name"), false);
  144. _([true, "Truth!", 1, false, '', 0]).each(function(value) {
  145. a.set({'name': value});
  146. equal(a.has("name"), true);
  147. });
  148. a.unset('name');
  149. equal(a.has('name'), false);
  150. _([null, undefined]).each(function(value) {
  151. a.set({'name': value});
  152. equal(a.has("name"), false);
  153. });
  154. });
  155. test("Model: set and unset", function() {
  156. expect(8);
  157. attrs = {id: 'id', foo: 1, bar: 2, baz: 3};
  158. a = new Backbone.Model(attrs);
  159. var changeCount = 0;
  160. a.on("change:foo", function() { changeCount += 1; });
  161. a.set({'foo': 2});
  162. ok(a.get('foo') == 2, "Foo should have changed.");
  163. ok(changeCount == 1, "Change count should have incremented.");
  164. a.set({'foo': 2}); // set with value that is not new shouldn't fire change event
  165. ok(a.get('foo') == 2, "Foo should NOT have changed, still 2");
  166. ok(changeCount == 1, "Change count should NOT have incremented.");
  167. a.validate = function(attrs) {
  168. equal(attrs.foo, void 0, "don't ignore values when unsetting");
  169. };
  170. a.unset('foo');
  171. equal(a.get('foo'), void 0, "Foo should have changed");
  172. delete a.validate;
  173. ok(changeCount == 2, "Change count should have incremented for unset.");
  174. a.unset('id');
  175. equal(a.id, undefined, "Unsetting the id should remove the id property.");
  176. });
  177. test("Model: multiple unsets", function() {
  178. var i = 0;
  179. var counter = function(){ i++; };
  180. var model = new Backbone.Model({a: 1});
  181. model.on("change:a", counter);
  182. model.set({a: 2});
  183. model.unset('a');
  184. model.unset('a');
  185. equal(i, 2, 'Unset does not fire an event for missing attributes.');
  186. });
  187. test("Model: unset and changedAttributes", function() {
  188. var model = new Backbone.Model({a: 1});
  189. model.unset('a', {silent: true});
  190. var changedAttributes = model.changedAttributes();
  191. ok('a' in changedAttributes, 'changedAttributes should contain unset properties');
  192. changedAttributes = model.changedAttributes();
  193. ok('a' in changedAttributes, 'changedAttributes should contain unset properties when running changedAttributes again after an unset.');
  194. });
  195. test("Model: using a non-default id attribute.", function() {
  196. var MongoModel = Backbone.Model.extend({idAttribute : '_id'});
  197. var model = new MongoModel({id: 'eye-dee', _id: 25, title: 'Model'});
  198. equal(model.get('id'), 'eye-dee');
  199. equal(model.id, 25);
  200. equal(model.isNew(), false);
  201. model.unset('_id');
  202. equal(model.id, undefined);
  203. equal(model.isNew(), true);
  204. });
  205. test("Model: set an empty string", function() {
  206. var model = new Backbone.Model({name : "Model"});
  207. model.set({name : ''});
  208. equal(model.get('name'), '');
  209. });
  210. test("Model: clear", function() {
  211. var changed;
  212. var model = new Backbone.Model({id: 1, name : "Model"});
  213. model.on("change:name", function(){ changed = true; });
  214. model.on("change", function() {
  215. var changedAttrs = model.changedAttributes();
  216. ok('name' in changedAttrs);
  217. });
  218. model.clear();
  219. equal(changed, true);
  220. equal(model.get('name'), undefined);
  221. });
  222. test("Model: defaults", function() {
  223. var Defaulted = Backbone.Model.extend({
  224. defaults: {
  225. "one": 1,
  226. "two": 2
  227. }
  228. });
  229. var model = new Defaulted({two: null});
  230. equal(model.get('one'), 1);
  231. equal(model.get('two'), null);
  232. Defaulted = Backbone.Model.extend({
  233. defaults: function() {
  234. return {
  235. "one": 3,
  236. "two": 4
  237. };
  238. }
  239. });
  240. var model = new Defaulted({two: null});
  241. equal(model.get('one'), 3);
  242. equal(model.get('two'), null);
  243. });
  244. test("Model: change, hasChanged, changedAttributes, previous, previousAttributes", function() {
  245. var model = new Backbone.Model({name : "Tim", age : 10});
  246. equal(model.changedAttributes(), false);
  247. model.on('change', function() {
  248. ok(model.hasChanged('name'), 'name changed');
  249. ok(!model.hasChanged('age'), 'age did not');
  250. ok(_.isEqual(model.changedAttributes(), {name : 'Rob'}), 'changedAttributes returns the changed attrs');
  251. equal(model.previous('name'), 'Tim');
  252. ok(_.isEqual(model.previousAttributes(), {name : "Tim", age : 10}), 'previousAttributes is correct');
  253. });
  254. model.set({name : 'Rob'}, {silent : true});
  255. equal(model.hasChanged(), true);
  256. equal(model.hasChanged('name'), true);
  257. model.change();
  258. equal(model.get('name'), 'Rob');
  259. });
  260. test("Model: changedAttributes", function() {
  261. var model = new Backbone.Model({a: 'a', b: 'b'});
  262. equal(model.changedAttributes(), false);
  263. equal(model.changedAttributes({a: 'a'}), false);
  264. equal(model.changedAttributes({a: 'b'}).a, 'b');
  265. });
  266. test("Model: change with options", function() {
  267. var value;
  268. var model = new Backbone.Model({name: 'Rob'});
  269. model.on('change', function(model, options) {
  270. value = options.prefix + model.get('name');
  271. });
  272. model.set({name: 'Bob'}, {silent: true});
  273. model.change({prefix: 'Mr. '});
  274. equal(value, 'Mr. Bob');
  275. model.set({name: 'Sue'}, {prefix: 'Ms. '});
  276. equal(value, 'Ms. Sue');
  277. });
  278. test("Model: change after initialize", function () {
  279. var changed = 0;
  280. var attrs = {id: 1, label: 'c'};
  281. var obj = new Backbone.Model(attrs);
  282. obj.on('change', function() { changed += 1; });
  283. obj.set(attrs);
  284. equal(changed, 0);
  285. });
  286. test("Model: save within change event", function () {
  287. var model = new Backbone.Model({firstName : "Taylor", lastName: "Swift"});
  288. model.on('change', function () {
  289. model.save();
  290. ok(_.isEqual(lastRequest[1], model));
  291. });
  292. model.set({lastName: 'Hicks'});
  293. });
  294. test("Model: validate after save", function() {
  295. var lastError, model = new Backbone.Model();
  296. model.validate = function(attrs) {
  297. if (attrs.admin) return "Can't change admin status.";
  298. };
  299. model.sync = function(method, model, options) {
  300. options.success.call(this, {admin: true});
  301. };
  302. model.save(null, {error: function(model, error) {
  303. lastError = error;
  304. }});
  305. equal(lastError, "Can't change admin status.");
  306. });
  307. test("Model: isValid", function() {
  308. var model = new Backbone.Model({valid: true});
  309. model.validate = function(attrs) {
  310. if (!attrs.valid) return "invalid";
  311. };
  312. equal(model.isValid(), true);
  313. equal(model.set({valid: false}), false);
  314. equal(model.isValid(), true);
  315. ok(model.set('valid', false, {silent: true}));
  316. equal(model.isValid(), false);
  317. });
  318. test("Model: save", function() {
  319. doc.save({title : "Henry V"});
  320. equal(lastRequest[0], 'update');
  321. ok(_.isEqual(lastRequest[1], doc));
  322. });
  323. test("Model: save in positional style", function() {
  324. var model = new Backbone.Model();
  325. model.sync = function(method, model, options) {
  326. options.success();
  327. };
  328. model.save('title', 'Twelfth Night');
  329. equal(model.get('title'), 'Twelfth Night');
  330. });
  331. test("Model: fetch", function() {
  332. doc.fetch();
  333. equal(lastRequest[0], 'read');
  334. ok(_.isEqual(lastRequest[1], doc));
  335. });
  336. test("Model: destroy", function() {
  337. doc.destroy();
  338. equal(lastRequest[0], 'delete');
  339. ok(_.isEqual(lastRequest[1], doc));
  340. });
  341. test("Model: non-persisted destroy", function() {
  342. attrs = { 'foo': 1, 'bar': 2, 'baz': 3};
  343. a = new Backbone.Model(attrs);
  344. a.sync = function() { throw "should not be called"; };
  345. a.destroy();
  346. ok(true, "non-persisted model should not call sync");
  347. });
  348. test("Model: validate", function() {
  349. var lastError;
  350. var model = new Backbone.Model();
  351. model.validate = function(attrs) {
  352. if (attrs.admin != this.get('admin')) return "Can't change admin status.";
  353. };
  354. model.on('error', function(model, error) {
  355. lastError = error;
  356. });
  357. var result = model.set({a: 100});
  358. equal(result, model);
  359. equal(model.get('a'), 100);
  360. equal(lastError, undefined);
  361. result = model.set({admin: true}, {silent: true});
  362. equal(model.get('admin'), true);
  363. result = model.set({a: 200, admin: false});
  364. equal(lastError, "Can't change admin status.");
  365. equal(result, false);
  366. equal(model.get('a'), 100);
  367. });
  368. test("Model: validate on unset and clear", function() {
  369. var error;
  370. var model = new Backbone.Model({name: "One"});
  371. model.validate = function(attrs) {
  372. if (!attrs.name) {
  373. error = true;
  374. return "No thanks.";
  375. }
  376. };
  377. model.set({name: "Two"});
  378. equal(model.get('name'), 'Two');
  379. equal(error, undefined);
  380. model.unset('name');
  381. equal(error, true);
  382. equal(model.get('name'), 'Two');
  383. model.clear();
  384. equal(model.get('name'), 'Two');
  385. delete model.validate;
  386. model.clear();
  387. equal(model.get('name'), undefined);
  388. });
  389. test("Model: validate with error callback", function() {
  390. var lastError, boundError;
  391. var model = new Backbone.Model();
  392. model.validate = function(attrs) {
  393. if (attrs.admin) return "Can't change admin status.";
  394. };
  395. var callback = function(model, error) {
  396. lastError = error;
  397. };
  398. model.on('error', function(model, error) {
  399. boundError = true;
  400. });
  401. var result = model.set({a: 100}, {error: callback});
  402. equal(result, model);
  403. equal(model.get('a'), 100);
  404. equal(lastError, undefined);
  405. equal(boundError, undefined);
  406. result = model.set({a: 200, admin: true}, {error: callback});
  407. equal(result, false);
  408. equal(model.get('a'), 100);
  409. equal(lastError, "Can't change admin status.");
  410. equal(boundError, undefined);
  411. });
  412. test("Model: defaults always extend attrs (#459)", function() {
  413. var Defaulted = Backbone.Model.extend({
  414. defaults: {one: 1},
  415. initialize : function(attrs, opts) {
  416. equal(this.attributes.one, 1);
  417. }
  418. });
  419. var providedattrs = new Defaulted({});
  420. var emptyattrs = new Defaulted();
  421. });
  422. test("Model: Inherit class properties", function() {
  423. var Parent = Backbone.Model.extend({
  424. instancePropSame: function() {},
  425. instancePropDiff: function() {}
  426. }, {
  427. classProp: function() {}
  428. });
  429. var Child = Parent.extend({
  430. instancePropDiff: function() {}
  431. });
  432. var adult = new Parent;
  433. var kid = new Child;
  434. equal(Child.classProp, Parent.classProp);
  435. notEqual(Child.classProp, undefined);
  436. equal(kid.instancePropSame, adult.instancePropSame);
  437. notEqual(kid.instancePropSame, undefined);
  438. notEqual(Child.prototype.instancePropDiff, Parent.prototype.instancePropDiff);
  439. notEqual(Child.prototype.instancePropDiff, undefined);
  440. });
  441. test("Model: Nested change events don't clobber previous attributes", function() {
  442. var A = Backbone.Model.extend({
  443. initialize: function() {
  444. this.on("change:state", function(a, newState) {
  445. equal(a.previous('state'), undefined);
  446. equal(newState, 'hello');
  447. // Fire a nested change event.
  448. this.set({ other: "whatever" });
  449. });
  450. }
  451. });
  452. var B = Backbone.Model.extend({
  453. initialize: function() {
  454. this.get("a").on("change:state", function(a, newState) {
  455. equal(a.previous('state'), undefined);
  456. equal(newState, 'hello');
  457. });
  458. }
  459. });
  460. a = new A();
  461. b = new B({a: a});
  462. a.set({state: 'hello'});
  463. });
  464. test("hasChanged/set should use same comparison", function() {
  465. expect(2);
  466. var changed = 0, model = new Backbone.Model({a: null});
  467. model.on('change', function() {
  468. ok(this.hasChanged('a'));
  469. })
  470. .on('change:a', function() {
  471. changed++;
  472. })
  473. .set({a: undefined});
  474. equal(changed, 1);
  475. });
  476. test("#582, #425, change:attribute callbacks should fire after all changes have occurred", 9, function() {
  477. var model = new Backbone.Model;
  478. var assertion = function() {
  479. equal(model.get('a'), 'a');
  480. equal(model.get('b'), 'b');
  481. equal(model.get('c'), 'c');
  482. };
  483. model.on('change:a', assertion);
  484. model.on('change:b', assertion);
  485. model.on('change:c', assertion);
  486. model.set({a: 'a', b: 'b', c: 'c'});
  487. });
  488. test("#871, set with attributes property", function() {
  489. var model = new Backbone.Model();
  490. model.set({attributes: true});
  491. ok(model.has('attributes'));
  492. });
  493. test("set value regardless of equality/change", function() {
  494. var model = new Backbone.Model({x: []});
  495. var a = [];
  496. model.set({x: a});
  497. ok(model.get('x') === a);
  498. });
  499. test("unset fires change for undefined attributes", 1, function() {
  500. var model = new Backbone.Model({x: undefined});
  501. model.on('change:x', function(){ ok(true); });
  502. model.unset('x');
  503. });
  504. test("set: undefined values", function() {
  505. var model = new Backbone.Model({x: undefined});
  506. ok('x' in model.attributes);
  507. });
  508. test("change fires change:attr", 1, function() {
  509. var model = new Backbone.Model({x: 1});
  510. model.set({x: 2}, {silent: true});
  511. model.on('change:x', function(){ ok(true); });
  512. model.change();
  513. });
  514. test("hasChanged is false after original values are set", function() {
  515. var model = new Backbone.Model({x: 1});
  516. model.on('change:x', function(){ ok(false); });
  517. model.set({x: 2}, {silent: true});
  518. ok(model.hasChanged());
  519. model.set({x: 1}, {silent: true});
  520. ok(!model.hasChanged());
  521. });
  522. test("set/hasChanged object prototype props", function() {
  523. var model = new Backbone.Model();
  524. ok(!model.hasChanged('toString'));
  525. model.set({toString: undefined});
  526. model.unset('toString', {silent: true});
  527. ok(model.hasChanged());
  528. });
  529. test("save with `wait` succeeds without `validate`", function() {
  530. var model = new Backbone.Model();
  531. model.save({x: 1}, {wait: true});
  532. ok(lastRequest[1] === model);
  533. });
  534. test("`hasChanged` for falsey keys", function() {
  535. var model = new Backbone.Model();
  536. model.set({x: true}, {silent: true});
  537. ok(!model.hasChanged(0));
  538. ok(!model.hasChanged(''));
  539. });
  540. test("`previous` for falsey keys", function() {
  541. var model = new Backbone.Model({0: true, '': true});
  542. model.set({0: false, '': false}, {silent: true});
  543. equal(model.previous(0), true);
  544. equal(model.previous(''), true);
  545. });
  546. test("`save` with `wait` sends correct attributes", function() {
  547. var changed = 0;
  548. var model = new Backbone.Model({x: 1, y: 2});
  549. model.on('change:x', function() { changed++; });
  550. model.save({x: 3}, {wait: true});
  551. deepEqual(JSON.parse(ajaxParams.data), {x: 3, y: 2});
  552. equal(model.get('x'), 1);
  553. equal(changed, 0);
  554. lastRequest[2].success({});
  555. equal(model.get('x'), 3);
  556. equal(changed, 1);
  557. });
  558. test("nested `set` during `'change:attr'`", 1, function() {
  559. var model = new Backbone.Model();
  560. model.on('change:x', function() { ok(true); });
  561. model.on('change:y', function() {
  562. model.set({x: true});
  563. // only fires once
  564. model.set({x: true});
  565. });
  566. model.set({y: true});
  567. });
  568. test("nested `change` only fires once", 1, function() {
  569. var model = new Backbone.Model();
  570. model.on('change', function() {
  571. ok(true);
  572. model.change();
  573. });
  574. model.set({x: true});
  575. });
  576. test("no `'change'` event if no changes", function() {
  577. var model = new Backbone.Model();
  578. model.on('change', function() { ok(false); });
  579. model.change();
  580. });
  581. test("nested `set` suring `'change'`", 3, function() {
  582. var count = 0;
  583. var model = new Backbone.Model();
  584. model.on('change', function() {
  585. switch(count++) {
  586. case 0:
  587. deepEqual(this.changedAttributes(), {x: true});
  588. model.set({y: true});
  589. break;
  590. case 1:
  591. deepEqual(this.changedAttributes(), {x: true, y: true});
  592. model.set({z: true});
  593. break;
  594. case 2:
  595. deepEqual(this.changedAttributes(), {x: true, y: true, z: true});
  596. break;
  597. default:
  598. ok(false);
  599. }
  600. });
  601. model.set({x: true});
  602. });
  603. });