PageRenderTime 59ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/test/model.js

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