PageRenderTime 52ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/test/model.js

https://github.com/pmichelberger/backbone
JavaScript | 483 lines | 428 code | 52 blank | 3 comment | 12 complexity | 21672d94d6139599ad04eb13a975bd66 MD5 | raw file
  1. $(document).ready(function() {
  2. module("Backbone.Model");
  3. // Variable to catch the last request.
  4. window.lastRequest = null;
  5. window.originalSync = Backbone.sync;
  6. // Stub out Backbone.request...
  7. Backbone.sync = function() {
  8. lastRequest = _.toArray(arguments);
  9. };
  10. var attrs = {
  11. id : '1-the-tempest',
  12. title : "The Tempest",
  13. author : "Bill Shakespeare",
  14. length : 123
  15. };
  16. var proxy = Backbone.Model.extend();
  17. var doc = new proxy(attrs);
  18. var klass = Backbone.Collection.extend({
  19. url : function() { return '/collection'; }
  20. });
  21. var collection = new klass();
  22. collection.add(doc);
  23. test("Model: initialize", function() {
  24. var Model = Backbone.Model.extend({
  25. initialize: function() {
  26. this.one = 1;
  27. equals(this.collection, collection);
  28. }
  29. });
  30. var model = new Model({}, {collection: collection});
  31. equals(model.one, 1);
  32. equals(model.collection, collection);
  33. });
  34. test("Model: initialize with attributes and options", function() {
  35. var Model = Backbone.Model.extend({
  36. initialize: function(attributes, options) {
  37. this.one = options.one;
  38. }
  39. });
  40. var model = new Model({}, {one: 1});
  41. equals(model.one, 1);
  42. });
  43. test("Model: initialize with parsed attributes", function() {
  44. var Model = Backbone.Model.extend({
  45. parse: function(obj) {
  46. obj.value += 1;
  47. return obj;
  48. }
  49. });
  50. var model = new Model({value: 1}, {parse: true});
  51. equals(model.get('value'), 2);
  52. });
  53. test("Model: url", function() {
  54. equals(doc.url(), '/collection/1-the-tempest');
  55. doc.collection.url = '/collection/';
  56. equals(doc.url(), '/collection/1-the-tempest');
  57. doc.collection = null;
  58. var failed = false;
  59. try {
  60. doc.url();
  61. } catch (e) {
  62. failed = true;
  63. }
  64. equals(failed, true);
  65. doc.collection = collection;
  66. });
  67. test("Model: url when using urlRoot, and uri encoding", function() {
  68. var Model = Backbone.Model.extend({
  69. urlRoot: '/collection'
  70. });
  71. var model = new Model();
  72. equals(model.url(), '/collection');
  73. model.set({id: '+1+'});
  74. equals(model.url(), '/collection/%2B1%2B');
  75. });
  76. test("Model: clone", function() {
  77. attrs = { 'foo': 1, 'bar': 2, 'baz': 3};
  78. a = new Backbone.Model(attrs);
  79. b = a.clone();
  80. equals(a.get('foo'), 1);
  81. equals(a.get('bar'), 2);
  82. equals(a.get('baz'), 3);
  83. equals(b.get('foo'), a.get('foo'), "Foo should be the same on the clone.");
  84. equals(b.get('bar'), a.get('bar'), "Bar should be the same on the clone.");
  85. equals(b.get('baz'), a.get('baz'), "Baz should be the same on the clone.");
  86. a.set({foo : 100});
  87. equals(a.get('foo'), 100);
  88. equals(b.get('foo'), 1, "Changing a parent attribute does not change the clone.");
  89. });
  90. test("Model: isNew", function() {
  91. attrs = { 'foo': 1, 'bar': 2, 'baz': 3};
  92. a = new Backbone.Model(attrs);
  93. ok(a.isNew(), "it should be new");
  94. attrs = { 'foo': 1, 'bar': 2, 'baz': 3, 'id': -5 };
  95. a = new Backbone.Model(attrs);
  96. ok(!a.isNew(), "any defined ID is legal, negative or positive");
  97. attrs = { 'foo': 1, 'bar': 2, 'baz': 3, 'id': 0 };
  98. a = new Backbone.Model(attrs);
  99. ok(!a.isNew(), "any defined ID is legal, including zero");
  100. ok( new Backbone.Model({ }).isNew(), "is true when there is no id");
  101. ok(!new Backbone.Model({ 'id': 2 }).isNew(), "is false for a positive integer");
  102. ok(!new Backbone.Model({ 'id': -5 }).isNew(), "is false for a negative integer");
  103. });
  104. test("Model: get", function() {
  105. equals(doc.get('title'), 'The Tempest');
  106. equals(doc.get('author'), 'Bill Shakespeare');
  107. });
  108. test("Model: escape", function() {
  109. equals(doc.escape('title'), 'The Tempest');
  110. doc.set({audience: 'Bill & Bob'});
  111. equals(doc.escape('audience'), 'Bill & Bob');
  112. doc.set({audience: 'Tim > Joan'});
  113. equals(doc.escape('audience'), 'Tim > Joan');
  114. doc.set({audience: 10101});
  115. equals(doc.escape('audience'), '10101');
  116. doc.unset('audience');
  117. equals(doc.escape('audience'), '');
  118. });
  119. test("Model: has", function() {
  120. attrs = {};
  121. a = new Backbone.Model(attrs);
  122. equals(a.has("name"), false);
  123. _([true, "Truth!", 1, false, '', 0]).each(function(value) {
  124. a.set({'name': value});
  125. equals(a.has("name"), true);
  126. });
  127. a.unset('name');
  128. equals(a.has('name'), false);
  129. _([null, undefined]).each(function(value) {
  130. a.set({'name': value});
  131. equals(a.has("name"), false);
  132. });
  133. });
  134. test("Model: set and unset", function() {
  135. expect(8);
  136. attrs = {id: 'id', foo: 1, bar: 2, baz: 3};
  137. a = new Backbone.Model(attrs);
  138. var changeCount = 0;
  139. a.bind("change:foo", function() { changeCount += 1; });
  140. a.set({'foo': 2});
  141. ok(a.get('foo') == 2, "Foo should have changed.");
  142. ok(changeCount == 1, "Change count should have incremented.");
  143. a.set({'foo': 2}); // set with value that is not new shouldn't fire change event
  144. ok(a.get('foo') == 2, "Foo should NOT have changed, still 2");
  145. ok(changeCount == 1, "Change count should NOT have incremented.");
  146. a.validate = function(attrs) {
  147. equals(attrs.foo, void 0, 'ignore values when unsetting');
  148. };
  149. a.unset('foo');
  150. ok(a.get('foo') == null, "Foo should have changed");
  151. delete a.validate;
  152. ok(changeCount == 2, "Change count should have incremented for unset.");
  153. a.unset('id');
  154. equals(a.id, undefined, "Unsetting the id should remove the id property.");
  155. });
  156. test("Model: multiple unsets", function() {
  157. var i = 0;
  158. var counter = function(){ i++; };
  159. var model = new Backbone.Model({a: 1});
  160. model.bind("change:a", counter);
  161. model.set({a: 2});
  162. model.unset('a');
  163. model.unset('a');
  164. equals(i, 2, 'Unset does not fire an event for missing attributes.');
  165. });
  166. test("Model: unset and changedAttributes", function() {
  167. var model = new Backbone.Model({a: 1});
  168. model.unset('a', {silent: true});
  169. var changedAttributes = model.changedAttributes();
  170. ok('a' in changedAttributes, 'changedAttributes should contain unset properties');
  171. changedAttributes = model.changedAttributes();
  172. ok('a' in changedAttributes, 'changedAttributes should contain unset properties when running changedAttributes again after an unset.');
  173. });
  174. test("Model: using a non-default id attribute.", function() {
  175. var MongoModel = Backbone.Model.extend({idAttribute : '_id'});
  176. var model = new MongoModel({id: 'eye-dee', _id: 25, title: 'Model'});
  177. equals(model.get('id'), 'eye-dee');
  178. equals(model.id, 25);
  179. equals(model.isNew(), false);
  180. model.unset('_id');
  181. equals(model.id, undefined);
  182. equals(model.isNew(), true);
  183. });
  184. test("Model: set an empty string", function() {
  185. var model = new Backbone.Model({name : "Model"});
  186. model.set({name : ''});
  187. equals(model.get('name'), '');
  188. });
  189. test("Model: clear", function() {
  190. var changed;
  191. var model = new Backbone.Model({id: 1, name : "Model"});
  192. model.bind("change:name", function(){ changed = true; });
  193. model.bind("change", function() {
  194. var changedAttrs = model.changedAttributes();
  195. ok('name' in changedAttrs);
  196. });
  197. model.clear();
  198. equals(changed, true);
  199. equals(model.get('name'), undefined);
  200. });
  201. test("Model: defaults", function() {
  202. var Defaulted = Backbone.Model.extend({
  203. defaults: {
  204. "one": 1,
  205. "two": 2
  206. }
  207. });
  208. var model = new Defaulted({two: null});
  209. equals(model.get('one'), 1);
  210. equals(model.get('two'), null);
  211. Defaulted = Backbone.Model.extend({
  212. defaults: function() {
  213. return {
  214. "one": 3,
  215. "two": 4
  216. };
  217. }
  218. });
  219. var model = new Defaulted({two: null});
  220. equals(model.get('one'), 3);
  221. equals(model.get('two'), null);
  222. });
  223. test("Model: change, hasChanged, changedAttributes, previous, previousAttributes", function() {
  224. var model = new Backbone.Model({name : "Tim", age : 10});
  225. equals(model.changedAttributes(), false);
  226. model.bind('change', function() {
  227. ok(model.hasChanged('name'), 'name changed');
  228. ok(!model.hasChanged('age'), 'age did not');
  229. ok(_.isEqual(model.changedAttributes(), {name : 'Rob'}), 'changedAttributes returns the changed attrs');
  230. equals(model.previous('name'), 'Tim');
  231. ok(_.isEqual(model.previousAttributes(), {name : "Tim", age : 10}), 'previousAttributes is correct');
  232. });
  233. model.set({name : 'Rob'}, {silent : true});
  234. equals(model.hasChanged(), true);
  235. equals(model.hasChanged('name'), true);
  236. model.change();
  237. equals(model.get('name'), 'Rob');
  238. });
  239. test("Model: change with options", function() {
  240. var value;
  241. var model = new Backbone.Model({name: 'Rob'});
  242. model.bind('change', function(model, options) {
  243. value = options.prefix + model.get('name');
  244. });
  245. model.set({name: 'Bob'}, {silent: true});
  246. model.change({prefix: 'Mr. '});
  247. equals(value, 'Mr. Bob');
  248. model.set({name: 'Sue'}, {prefix: 'Ms. '});
  249. equals(value, 'Ms. Sue');
  250. });
  251. test("Model: change after initialize", function () {
  252. var changed = 0;
  253. var attrs = {id: 1, label: 'c'};
  254. var obj = new Backbone.Model(attrs);
  255. obj.bind('change', function() { changed += 1; });
  256. obj.set(attrs);
  257. equals(changed, 0);
  258. });
  259. test("Model: save within change event", function () {
  260. var model = new Backbone.Model({firstName : "Taylor", lastName: "Swift"});
  261. model.bind('change', function () {
  262. model.save();
  263. ok(_.isEqual(lastRequest[1], model));
  264. });
  265. model.set({lastName: 'Hicks'});
  266. });
  267. test("Model: validate after save", function() {
  268. var lastError, model = new Backbone.Model();
  269. model.validate = function(attrs) {
  270. if (attrs.admin) return "Can't change admin status.";
  271. };
  272. model.sync = function(method, model, options) {
  273. options.success.call(this, {admin: true});
  274. };
  275. model.save(null, {error: function(model, error) {
  276. console.log('erroring!');
  277. lastError = error;
  278. }});
  279. equals(lastError, "Can't change admin status.");
  280. });
  281. test("Model: save", function() {
  282. doc.save({title : "Henry V"});
  283. equals(lastRequest[0], 'update');
  284. ok(_.isEqual(lastRequest[1], doc));
  285. });
  286. test("Model: fetch", function() {
  287. doc.fetch();
  288. ok(lastRequest[0], 'read');
  289. ok(_.isEqual(lastRequest[1], doc));
  290. });
  291. test("Model: destroy", function() {
  292. doc.destroy();
  293. equals(lastRequest[0], 'delete');
  294. ok(_.isEqual(lastRequest[1], doc));
  295. });
  296. test("Model: non-persisted destroy", function() {
  297. attrs = { 'foo': 1, 'bar': 2, 'baz': 3};
  298. a = new Backbone.Model(attrs);
  299. a.sync = function() { throw "should not be called"; };
  300. ok(a.destroy(), "non-persisted model should not call sync");
  301. });
  302. test("Model: validate", function() {
  303. var lastError;
  304. var model = new Backbone.Model();
  305. model.validate = function(attrs) {
  306. if (attrs.admin) return "Can't change admin status.";
  307. };
  308. model.bind('error', function(model, error) {
  309. lastError = error;
  310. });
  311. var result = model.set({a: 100});
  312. equals(result, model);
  313. equals(model.get('a'), 100);
  314. equals(lastError, undefined);
  315. result = model.set({admin: true}, {silent: true});
  316. equals(lastError, undefined);
  317. equals(model.get('admin'), true);
  318. result = model.set({a: 200, admin: true});
  319. equals(result, false);
  320. equals(model.get('a'), 100);
  321. equals(lastError, "Can't change admin status.");
  322. });
  323. test("Model: validate on unset and clear", function() {
  324. var error;
  325. var model = new Backbone.Model({name: "One"});
  326. model.validate = function(attrs) {
  327. if ("name" in attrs) {
  328. if (!attrs.name) {
  329. error = true;
  330. return "No thanks.";
  331. }
  332. }
  333. };
  334. model.set({name: "Two"});
  335. equals(model.get('name'), 'Two');
  336. equals(error, undefined);
  337. model.unset('name');
  338. equals(error, true);
  339. equals(model.get('name'), 'Two');
  340. model.clear();
  341. equals(model.get('name'), 'Two');
  342. delete model.validate;
  343. model.clear();
  344. equals(model.get('name'), undefined);
  345. });
  346. test("Model: validate with error callback", function() {
  347. var lastError, boundError;
  348. var model = new Backbone.Model();
  349. model.validate = function(attrs) {
  350. if (attrs.admin) return "Can't change admin status.";
  351. };
  352. var callback = function(model, error) {
  353. lastError = error;
  354. };
  355. model.bind('error', function(model, error) {
  356. boundError = true;
  357. });
  358. var result = model.set({a: 100}, {error: callback});
  359. equals(result, model);
  360. equals(model.get('a'), 100);
  361. equals(lastError, undefined);
  362. equals(boundError, undefined);
  363. result = model.set({a: 200, admin: true}, {error: callback});
  364. equals(result, false);
  365. equals(model.get('a'), 100);
  366. equals(lastError, "Can't change admin status.");
  367. equals(boundError, undefined);
  368. });
  369. test("Model: defaults always extend attrs (#459)", function() {
  370. var Defaulted = Backbone.Model.extend({
  371. defaults: {one: 1},
  372. initialize : function(attrs, opts) {
  373. equals(attrs.one, 1);
  374. }
  375. });
  376. var providedattrs = new Defaulted({});
  377. var emptyattrs = new Defaulted();
  378. });
  379. test("Model: Inherit class properties", function() {
  380. var Parent = Backbone.Model.extend({
  381. instancePropSame: function() {},
  382. instancePropDiff: function() {}
  383. }, {
  384. classProp: function() {}
  385. });
  386. var Child = Parent.extend({
  387. instancePropDiff: function() {}
  388. });
  389. var adult = new Parent;
  390. var kid = new Child;
  391. equals(Child.classProp, Parent.classProp);
  392. notEqual(Child.classProp, undefined);
  393. equals(kid.instancePropSame, adult.instancePropSame);
  394. notEqual(kid.instancePropSame, undefined);
  395. notEqual(Child.prototype.instancePropDiff, Parent.prototype.instancePropDiff);
  396. notEqual(Child.prototype.instancePropDiff, undefined);
  397. });
  398. test("Model: Nested change events don't clobber previous attributes", function() {
  399. var A = Backbone.Model.extend({
  400. initialize: function() {
  401. this.bind("change:state", function(a, newState) {
  402. equals(a.previous('state'), undefined);
  403. equals(newState, 'hello');
  404. // Fire a nested change event.
  405. this.set({ other: "whatever" });
  406. });
  407. }
  408. });
  409. var B = Backbone.Model.extend({
  410. initialize: function() {
  411. this.get("a").bind("change:state", function(a, newState) {
  412. equals(a.previous('state'), undefined);
  413. equals(newState, 'hello');
  414. });
  415. }
  416. });
  417. a = new A();
  418. b = new B({a: a});
  419. a.set({state: 'hello'});
  420. });
  421. test("Model: Multiple nested calls to set", function() {
  422. var counter = 0, model = new Backbone.Model({});
  423. model.bind('change', function() {
  424. counter++;
  425. model.set({b: 1});
  426. model.set({a: 1});
  427. })
  428. .set({a: 1});
  429. equal(counter, 1, 'change is only triggered once');
  430. });
  431. });