PageRenderTime 186ms CodeModel.GetById 2ms app.highlight 159ms RepoModel.GetById 7ms app.codeStats 1ms

/test/model.js

https://gitlab.com/JJVV27/backbone
JavaScript | 1297 lines | 1148 code | 148 blank | 1 comment | 19 complexity | 5dfe76eabcd2d040ebe6ba2f34e08e50 MD5 | raw file
   1(function() {
   2
   3  var proxy = Backbone.Model.extend();
   4  var klass = Backbone.Collection.extend({
   5    url : function() { return '/collection'; }
   6  });
   7  var doc, collection;
   8
   9  module("Backbone.Model", {
  10
  11    setup: function() {
  12      doc = new proxy({
  13        id     : '1-the-tempest',
  14        title  : "The Tempest",
  15        author : "Bill Shakespeare",
  16        length : 123
  17      });
  18      collection = new klass();
  19      collection.add(doc);
  20    }
  21
  22  });
  23
  24  test("initialize", 3, function() {
  25    var Model = Backbone.Model.extend({
  26      initialize: function() {
  27        this.one = 1;
  28        equal(this.collection, collection);
  29      }
  30    });
  31    var model = new Model({}, {collection: collection});
  32    equal(model.one, 1);
  33    equal(model.collection, collection);
  34  });
  35
  36  test("initialize with attributes and options", 1, function() {
  37    var Model = Backbone.Model.extend({
  38      initialize: function(attributes, options) {
  39        this.one = options.one;
  40      }
  41    });
  42    var model = new Model({}, {one: 1});
  43    equal(model.one, 1);
  44  });
  45
  46  test("initialize with parsed attributes", 1, function() {
  47    var Model = Backbone.Model.extend({
  48      parse: function(attrs) {
  49        attrs.value += 1;
  50        return attrs;
  51      }
  52    });
  53    var model = new Model({value: 1}, {parse: true});
  54    equal(model.get('value'), 2);
  55  });
  56
  57  test("initialize with defaults", 2, function() {
  58    var Model = Backbone.Model.extend({
  59      defaults: {
  60        first_name: 'Unknown',
  61        last_name: 'Unknown'
  62      }
  63    });
  64    var model = new Model({'first_name': 'John'});
  65    equal(model.get('first_name'), 'John');
  66    equal(model.get('last_name'), 'Unknown');
  67  });
  68
  69  test("parse can return null", 1, function() {
  70    var Model = Backbone.Model.extend({
  71      parse: function(attrs) {
  72        attrs.value += 1;
  73        return null;
  74      }
  75    });
  76    var model = new Model({value: 1}, {parse: true});
  77    equal(JSON.stringify(model.toJSON()), "{}");
  78  });
  79
  80  test("url", 3, function() {
  81    doc.urlRoot = null;
  82    equal(doc.url(), '/collection/1-the-tempest');
  83    doc.collection.url = '/collection/';
  84    equal(doc.url(), '/collection/1-the-tempest');
  85    doc.collection = null;
  86    throws(function() { doc.url(); });
  87    doc.collection = collection;
  88  });
  89
  90  test("url when using urlRoot, and uri encoding", 2, function() {
  91    var Model = Backbone.Model.extend({
  92      urlRoot: '/collection'
  93    });
  94    var model = new Model();
  95    equal(model.url(), '/collection');
  96    model.set({id: '+1+'});
  97    equal(model.url(), '/collection/%2B1%2B');
  98  });
  99
 100  test("url when using urlRoot as a function to determine urlRoot at runtime", 2, function() {
 101    var Model = Backbone.Model.extend({
 102      urlRoot: function() {
 103        return '/nested/' + this.get('parent_id') + '/collection';
 104      }
 105    });
 106
 107    var model = new Model({parent_id: 1});
 108    equal(model.url(), '/nested/1/collection');
 109    model.set({id: 2});
 110    equal(model.url(), '/nested/1/collection/2');
 111  });
 112
 113  test("underscore methods", 5, function() {
 114    var model = new Backbone.Model({ 'foo': 'a', 'bar': 'b', 'baz': 'c' });
 115    var model2 = model.clone();
 116    deepEqual(model.keys(), ['foo', 'bar', 'baz']);
 117    deepEqual(model.values(), ['a', 'b', 'c']);
 118    deepEqual(model.invert(), { 'a': 'foo', 'b': 'bar', 'c': 'baz' });
 119    deepEqual(model.pick('foo', 'baz'), {'foo': 'a', 'baz': 'c'});
 120    deepEqual(model.omit('foo', 'bar'), {'baz': 'c'});
 121  });
 122
 123  test("chain", function() {
 124    var model = new Backbone.Model({ a: 0, b: 1, c: 2 });
 125    deepEqual(model.chain().pick("a", "b", "c").values().compact().value(), [1, 2]);
 126  });
 127
 128  test("clone", 10, function() {
 129    var a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3});
 130    var b = a.clone();
 131    equal(a.get('foo'), 1);
 132    equal(a.get('bar'), 2);
 133    equal(a.get('baz'), 3);
 134    equal(b.get('foo'), a.get('foo'), "Foo should be the same on the clone.");
 135    equal(b.get('bar'), a.get('bar'), "Bar should be the same on the clone.");
 136    equal(b.get('baz'), a.get('baz'), "Baz should be the same on the clone.");
 137    a.set({foo : 100});
 138    equal(a.get('foo'), 100);
 139    equal(b.get('foo'), 1, "Changing a parent attribute does not change the clone.");
 140
 141    var foo = new Backbone.Model({p: 1});
 142    var bar = new Backbone.Model({p: 2});
 143    bar.set(foo.clone().attributes, {unset: true});
 144    equal(foo.get('p'), 1);
 145    equal(bar.get('p'), undefined);
 146  });
 147
 148  test("isNew", 6, function() {
 149    var a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3});
 150    ok(a.isNew(), "it should be new");
 151    a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3, 'id': -5 });
 152    ok(!a.isNew(), "any defined ID is legal, negative or positive");
 153    a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3, 'id': 0 });
 154    ok(!a.isNew(), "any defined ID is legal, including zero");
 155    ok( new Backbone.Model({          }).isNew(), "is true when there is no id");
 156    ok(!new Backbone.Model({ 'id': 2  }).isNew(), "is false for a positive integer");
 157    ok(!new Backbone.Model({ 'id': -5 }).isNew(), "is false for a negative integer");
 158  });
 159
 160  test("get", 2, function() {
 161    equal(doc.get('title'), 'The Tempest');
 162    equal(doc.get('author'), 'Bill Shakespeare');
 163  });
 164
 165  test("escape", 5, function() {
 166    equal(doc.escape('title'), 'The Tempest');
 167    doc.set({audience: 'Bill & Bob'});
 168    equal(doc.escape('audience'), 'Bill & Bob');
 169    doc.set({audience: 'Tim > Joan'});
 170    equal(doc.escape('audience'), 'Tim > Joan');
 171    doc.set({audience: 10101});
 172    equal(doc.escape('audience'), '10101');
 173    doc.unset('audience');
 174    equal(doc.escape('audience'), '');
 175  });
 176
 177  test("has", 10, function() {
 178    var model = new Backbone.Model();
 179
 180    strictEqual(model.has('name'), false);
 181
 182    model.set({
 183      '0': 0,
 184      '1': 1,
 185      'true': true,
 186      'false': false,
 187      'empty': '',
 188      'name': 'name',
 189      'null': null,
 190      'undefined': undefined
 191    });
 192
 193    strictEqual(model.has('0'), true);
 194    strictEqual(model.has('1'), true);
 195    strictEqual(model.has('true'), true);
 196    strictEqual(model.has('false'), true);
 197    strictEqual(model.has('empty'), true);
 198    strictEqual(model.has('name'), true);
 199
 200    model.unset('name');
 201
 202    strictEqual(model.has('name'), false);
 203    strictEqual(model.has('null'), false);
 204    strictEqual(model.has('undefined'), false);
 205  });
 206
 207  test("matches", 4, function() {
 208    var model = new Backbone.Model();
 209
 210    strictEqual(model.matches({'name': 'Jonas', 'cool': true}), false);
 211
 212    model.set({name: 'Jonas', 'cool': true});
 213
 214    strictEqual(model.matches({'name': 'Jonas'}), true);
 215    strictEqual(model.matches({'name': 'Jonas', 'cool': true}), true);
 216    strictEqual(model.matches({'name': 'Jonas', 'cool': false}), false);
 217  });
 218
 219  test("matches with predicate", function() {
 220    var model = new Backbone.Model({a: 0});
 221
 222    strictEqual(model.matches(function(attr) {
 223      return attr.a > 1 && attr.b != null;
 224    }), false);
 225
 226    model.set({a: 3, b: true});
 227
 228    strictEqual(model.matches(function(attr) {
 229      return attr.a > 1 && attr.b != null;
 230    }), true);
 231  })
 232
 233  test("set and unset", 8, function() {
 234    var a = new Backbone.Model({id: 'id', foo: 1, bar: 2, baz: 3});
 235    var changeCount = 0;
 236    a.on("change:foo", function() { changeCount += 1; });
 237    a.set({'foo': 2});
 238    ok(a.get('foo') == 2, "Foo should have changed.");
 239    ok(changeCount == 1, "Change count should have incremented.");
 240    a.set({'foo': 2}); // set with value that is not new shouldn't fire change event
 241    ok(a.get('foo') == 2, "Foo should NOT have changed, still 2");
 242    ok(changeCount == 1, "Change count should NOT have incremented.");
 243
 244    a.validate = function(attrs) {
 245      equal(attrs.foo, void 0, "validate:true passed while unsetting");
 246    };
 247    a.unset('foo', {validate: true});
 248    equal(a.get('foo'), void 0, "Foo should have changed");
 249    delete a.validate;
 250    ok(changeCount == 2, "Change count should have incremented for unset.");
 251
 252    a.unset('id');
 253    equal(a.id, undefined, "Unsetting the id should remove the id property.");
 254  });
 255
 256  test("#2030 - set with failed validate, followed by another set triggers change", function () {
 257    var attr = 0, main = 0, error = 0;
 258    var Model = Backbone.Model.extend({
 259      validate: function (attr) {
 260        if (attr.x > 1) {
 261          error++;
 262          return "this is an error";
 263        }
 264      }
 265    });
 266    var model = new Model({x:0});
 267      model.on('change:x', function () { attr++; });
 268      model.on('change', function () { main++; });
 269      model.set({x:2}, {validate:true});
 270      model.set({x:1}, {validate:true});
 271      deepEqual([attr, main, error], [1, 1, 1]);
 272  });
 273
 274  test("set triggers changes in the correct order", function() {
 275    var value = null;
 276    var model = new Backbone.Model;
 277    model.on('last', function(){ value = 'last'; });
 278    model.on('first', function(){ value = 'first'; });
 279    model.trigger('first');
 280    model.trigger('last');
 281    equal(value, 'last');
 282  });
 283
 284  test("set falsy values in the correct order", 2, function() {
 285    var model = new Backbone.Model({result: 'result'});
 286    model.on('change', function() {
 287      equal(model.changed.result, void 0);
 288      equal(model.previous('result'), false);
 289    });
 290    model.set({result: void 0}, {silent: true});
 291    model.set({result: null}, {silent: true});
 292    model.set({result: false}, {silent: true});
 293    model.set({result: void 0});
 294  });
 295
 296  test("nested set triggers with the correct options", function() {
 297    var model = new Backbone.Model();
 298    var o1 = {};
 299    var o2 = {};
 300    var o3 = {};
 301    model.on('change', function(__, options) {
 302      switch (model.get('a')) {
 303      case 1:
 304        equal(options, o1);
 305        return model.set('a', 2, o2);
 306      case 2:
 307        equal(options, o2);
 308        return model.set('a', 3, o3);
 309      case 3:
 310        equal(options, o3);
 311      }
 312    });
 313    model.set('a', 1, o1);
 314  });
 315
 316  test("multiple unsets", 1, function() {
 317    var i = 0;
 318    var counter = function(){ i++; };
 319    var model = new Backbone.Model({a: 1});
 320    model.on("change:a", counter);
 321    model.set({a: 2});
 322    model.unset('a');
 323    model.unset('a');
 324    equal(i, 2, 'Unset does not fire an event for missing attributes.');
 325  });
 326
 327  test("unset and changedAttributes", 1, function() {
 328    var model = new Backbone.Model({a: 1});
 329    model.on('change', function() {
 330      ok('a' in model.changedAttributes(), 'changedAttributes should contain unset properties');
 331    });
 332    model.unset('a');
 333  });
 334
 335  test("using a non-default id attribute.", 5, function() {
 336    var MongoModel = Backbone.Model.extend({idAttribute : '_id'});
 337    var model = new MongoModel({id: 'eye-dee', _id: 25, title: 'Model'});
 338    equal(model.get('id'), 'eye-dee');
 339    equal(model.id, 25);
 340    equal(model.isNew(), false);
 341    model.unset('_id');
 342    equal(model.id, undefined);
 343    equal(model.isNew(), true);
 344  });
 345
 346  test("setting an alternative cid prefix", 4, function() {
 347    var Model = Backbone.Model.extend({
 348      cidPrefix: 'm'
 349    });
 350    var model = new Model();
 351
 352    equal(model.cid.charAt(0), 'm');
 353
 354    model = new Backbone.Model();
 355    equal(model.cid.charAt(0), 'c');
 356
 357    var Collection = Backbone.Collection.extend({
 358      model: Model
 359    });
 360    var collection = new Collection([{id: 'c5'}, {id: 'c6'}, {id: 'c7'}]);
 361
 362    equal(collection.get('c6').cid.charAt(0), 'm');
 363    collection.set([{id: 'c6', value: 'test'}], {
 364      merge: true,
 365      add: true,
 366      remove: false
 367    });
 368    ok(collection.get('c6').has('value'));
 369  });
 370
 371  test("set an empty string", 1, function() {
 372    var model = new Backbone.Model({name : "Model"});
 373    model.set({name : ''});
 374    equal(model.get('name'), '');
 375  });
 376
 377  test("setting an object", 1, function() {
 378    var model = new Backbone.Model({
 379      custom: { foo: 1 }
 380    });
 381    model.on('change', function() {
 382      ok(1);
 383    });
 384    model.set({
 385      custom: { foo: 1 } // no change should be fired
 386    });
 387    model.set({
 388      custom: { foo: 2 } // change event should be fired
 389    });
 390  });
 391
 392  test("clear", 3, function() {
 393    var changed;
 394    var model = new Backbone.Model({id: 1, name : "Model"});
 395    model.on("change:name", function(){ changed = true; });
 396    model.on("change", function() {
 397      var changedAttrs = model.changedAttributes();
 398      ok('name' in changedAttrs);
 399    });
 400    model.clear();
 401    equal(changed, true);
 402    equal(model.get('name'), undefined);
 403  });
 404
 405  test("defaults", 4, function() {
 406    var Defaulted = Backbone.Model.extend({
 407      defaults: {
 408        "one": 1,
 409        "two": 2
 410      }
 411    });
 412    var model = new Defaulted({two: undefined});
 413    equal(model.get('one'), 1);
 414    equal(model.get('two'), 2);
 415    Defaulted = Backbone.Model.extend({
 416      defaults: function() {
 417        return {
 418          "one": 3,
 419          "two": 4
 420        };
 421      }
 422    });
 423    model = new Defaulted({two: undefined});
 424    equal(model.get('one'), 3);
 425    equal(model.get('two'), 4);
 426  });
 427
 428  test("change, hasChanged, changedAttributes, previous, previousAttributes", 9, function() {
 429    var model = new Backbone.Model({name: "Tim", age: 10});
 430    deepEqual(model.changedAttributes(), false);
 431    model.on('change', function() {
 432      ok(model.hasChanged('name'), 'name changed');
 433      ok(!model.hasChanged('age'), 'age did not');
 434      ok(_.isEqual(model.changedAttributes(), {name : 'Rob'}), 'changedAttributes returns the changed attrs');
 435      equal(model.previous('name'), 'Tim');
 436      ok(_.isEqual(model.previousAttributes(), {name : "Tim", age : 10}), 'previousAttributes is correct');
 437    });
 438    equal(model.hasChanged(), false);
 439    equal(model.hasChanged(undefined), false);
 440    model.set({name : 'Rob'});
 441    equal(model.get('name'), 'Rob');
 442  });
 443
 444  test("changedAttributes", 3, function() {
 445    var model = new Backbone.Model({a: 'a', b: 'b'});
 446    deepEqual(model.changedAttributes(), false);
 447    equal(model.changedAttributes({a: 'a'}), false);
 448    equal(model.changedAttributes({a: 'b'}).a, 'b');
 449  });
 450
 451  test("change with options", 2, function() {
 452    var value;
 453    var model = new Backbone.Model({name: 'Rob'});
 454    model.on('change', function(model, options) {
 455      value = options.prefix + model.get('name');
 456    });
 457    model.set({name: 'Bob'}, {prefix: 'Mr. '});
 458    equal(value, 'Mr. Bob');
 459    model.set({name: 'Sue'}, {prefix: 'Ms. '});
 460    equal(value, 'Ms. Sue');
 461  });
 462
 463  test("change after initialize", 1, function () {
 464    var changed = 0;
 465    var attrs = {id: 1, label: 'c'};
 466    var obj = new Backbone.Model(attrs);
 467    obj.on('change', function() { changed += 1; });
 468    obj.set(attrs);
 469    equal(changed, 0);
 470  });
 471
 472  test("save within change event", 1, function () {
 473    var env = this;
 474    var model = new Backbone.Model({firstName : "Taylor", lastName: "Swift"});
 475    model.url = '/test';
 476    model.on('change', function () {
 477      model.save();
 478      ok(_.isEqual(env.syncArgs.model, model));
 479    });
 480    model.set({lastName: 'Hicks'});
 481  });
 482
 483  test("validate after save", 2, function() {
 484    var lastError, model = new Backbone.Model();
 485    model.validate = function(attrs) {
 486      if (attrs.admin) return "Can't change admin status.";
 487    };
 488    model.sync = function(method, model, options) {
 489      options.success.call(this, {admin: true});
 490    };
 491    model.on('invalid', function(model, error) {
 492      lastError = error;
 493    });
 494    model.save(null);
 495
 496    equal(lastError, "Can't change admin status.");
 497    equal(model.validationError, "Can't change admin status.");
 498  });
 499
 500  test("save", 2, function() {
 501    doc.save({title : "Henry V"});
 502    equal(this.syncArgs.method, 'update');
 503    ok(_.isEqual(this.syncArgs.model, doc));
 504  });
 505
 506  test("save, fetch, destroy triggers error event when an error occurs", 3, function () {
 507    var model = new Backbone.Model();
 508    model.on('error', function () {
 509      ok(true);
 510    });
 511    model.sync = function (method, model, options) {
 512      options.error();
 513    };
 514    model.save({data: 2, id: 1});
 515    model.fetch();
 516    model.destroy();
 517  });
 518
 519  test("#3283 - save, fetch, destroy calls success with context", 3, function () {
 520    var model = new Backbone.Model();
 521    var obj = {};
 522    var options = {
 523      context: obj,
 524      success: function() {
 525        equal(this, obj);
 526      }
 527    };
 528    model.sync = function (method, model, options) {
 529      options.success.call(options.context);
 530    };
 531    model.save({data: 2, id: 1}, options);
 532    model.fetch(options);
 533    model.destroy(options);
 534  });
 535
 536  test("#3283 - save, fetch, destroy calls error with context", 3, function () {
 537    var model = new Backbone.Model();
 538    var obj = {};
 539    var options = {
 540      context: obj,
 541      error: function() {
 542        equal(this, obj);
 543      }
 544    };
 545    model.sync = function (method, model, options) {
 546      options.error.call(options.context);
 547    };
 548    model.save({data: 2, id: 1}, options);
 549    model.fetch(options);
 550    model.destroy(options);
 551  });
 552
 553  test("save with PATCH", function() {
 554    doc.clear().set({id: 1, a: 1, b: 2, c: 3, d: 4});
 555    doc.save();
 556    equal(this.syncArgs.method, 'update');
 557    equal(this.syncArgs.options.attrs, undefined);
 558
 559    doc.save({b: 2, d: 4}, {patch: true});
 560    equal(this.syncArgs.method, 'patch');
 561    equal(_.size(this.syncArgs.options.attrs), 2);
 562    equal(this.syncArgs.options.attrs.d, 4);
 563    equal(this.syncArgs.options.attrs.a, undefined);
 564    equal(this.ajaxSettings.data, "{\"b\":2,\"d\":4}");
 565  });
 566
 567  test("save with PATCH and different attrs", function() {
 568    doc.clear().save({b: 2, d: 4}, {patch: true, attrs: {B: 1, D: 3}});
 569    equal(this.syncArgs.options.attrs.D, 3);
 570    equal(this.syncArgs.options.attrs.d, undefined);
 571    equal(this.ajaxSettings.data, "{\"B\":1,\"D\":3}");
 572    deepEqual(doc.attributes, {b: 2, d: 4});
 573  });
 574
 575  test("save in positional style", 1, function() {
 576    var model = new Backbone.Model();
 577    model.sync = function(method, model, options) {
 578      options.success();
 579    };
 580    model.save('title', 'Twelfth Night');
 581    equal(model.get('title'), 'Twelfth Night');
 582  });
 583
 584  test("save with non-object success response", 2, function () {
 585    var model = new Backbone.Model();
 586    model.sync = function(method, model, options) {
 587      options.success('', options);
 588      options.success(null, options);
 589    };
 590    model.save({testing:'empty'}, {
 591      success: function (model) {
 592        deepEqual(model.attributes, {testing:'empty'});
 593      }
 594    });
 595  });
 596
 597  test("save with wait and supplied id", function() {
 598    var Model = Backbone.Model.extend({
 599      urlRoot: '/collection'
 600    });
 601    var model = new Model();
 602    model.save({id: 42}, {wait: true});
 603    equal(this.ajaxSettings.url, '/collection/42');
 604  });
 605
 606  test("save will pass extra options to success callback", 1, function () {
 607    var SpecialSyncModel = Backbone.Model.extend({
 608      sync: function (method, model, options) {
 609        _.extend(options, { specialSync: true });
 610        return Backbone.Model.prototype.sync.call(this, method, model, options);
 611      },
 612      urlRoot: '/test'
 613    });
 614
 615    var model = new SpecialSyncModel();
 616
 617    var onSuccess = function (model, response, options) {
 618      ok(options.specialSync, "Options were passed correctly to callback");
 619    };
 620
 621    model.save(null, { success: onSuccess });
 622    this.ajaxSettings.success();
 623  });
 624
 625  test("fetch", 2, function() {
 626    doc.fetch();
 627    equal(this.syncArgs.method, 'read');
 628    ok(_.isEqual(this.syncArgs.model, doc));
 629  });
 630
 631  test("fetch will pass extra options to success callback", 1, function () {
 632    var SpecialSyncModel = Backbone.Model.extend({
 633      sync: function (method, model, options) {
 634        _.extend(options, { specialSync: true });
 635        return Backbone.Model.prototype.sync.call(this, method, model, options);
 636      },
 637      urlRoot: '/test'
 638    });
 639
 640    var model = new SpecialSyncModel();
 641
 642    var onSuccess = function (model, response, options) {
 643      ok(options.specialSync, "Options were passed correctly to callback");
 644    };
 645
 646    model.fetch({ success: onSuccess });
 647    this.ajaxSettings.success();
 648  });
 649
 650  test("destroy", 3, function() {
 651    doc.destroy();
 652    equal(this.syncArgs.method, 'delete');
 653    ok(_.isEqual(this.syncArgs.model, doc));
 654
 655    var newModel = new Backbone.Model;
 656    equal(newModel.destroy(), false);
 657  });
 658
 659  test("destroy will pass extra options to success callback", 1, function () {
 660    var SpecialSyncModel = Backbone.Model.extend({
 661      sync: function (method, model, options) {
 662        _.extend(options, { specialSync: true });
 663        return Backbone.Model.prototype.sync.call(this, method, model, options);
 664      },
 665      urlRoot: '/test'
 666    });
 667
 668    var model = new SpecialSyncModel({ id: 'id' });
 669
 670    var onSuccess = function (model, response, options) {
 671      ok(options.specialSync, "Options were passed correctly to callback");
 672    };
 673
 674    model.destroy({ success: onSuccess });
 675    this.ajaxSettings.success();
 676  });
 677
 678  test("non-persisted destroy", 1, function() {
 679    var a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3});
 680    a.sync = function() { throw "should not be called"; };
 681    a.destroy();
 682    ok(true, "non-persisted model should not call sync");
 683  });
 684
 685  test("validate", function() {
 686    var lastError;
 687    var model = new Backbone.Model();
 688    model.validate = function(attrs) {
 689      if (attrs.admin != this.get('admin')) return "Can't change admin status.";
 690    };
 691    model.on('invalid', function(model, error) {
 692      lastError = error;
 693    });
 694    var result = model.set({a: 100});
 695    equal(result, model);
 696    equal(model.get('a'), 100);
 697    equal(lastError, undefined);
 698    result = model.set({admin: true});
 699    equal(model.get('admin'), true);
 700    result = model.set({a: 200, admin: false}, {validate:true});
 701    equal(lastError, "Can't change admin status.");
 702    equal(result, false);
 703    equal(model.get('a'), 100);
 704  });
 705
 706  test("validate on unset and clear", 6, function() {
 707    var error;
 708    var model = new Backbone.Model({name: "One"});
 709    model.validate = function(attrs) {
 710      if (!attrs.name) {
 711        error = true;
 712        return "No thanks.";
 713      }
 714    };
 715    model.set({name: "Two"});
 716    equal(model.get('name'), 'Two');
 717    equal(error, undefined);
 718    model.unset('name', {validate: true});
 719    equal(error, true);
 720    equal(model.get('name'), 'Two');
 721    model.clear({validate:true});
 722    equal(model.get('name'), 'Two');
 723    delete model.validate;
 724    model.clear();
 725    equal(model.get('name'), undefined);
 726  });
 727
 728  test("validate with error callback", 8, function() {
 729    var lastError, boundError;
 730    var model = new Backbone.Model();
 731    model.validate = function(attrs) {
 732      if (attrs.admin) return "Can't change admin status.";
 733    };
 734    model.on('invalid', function(model, error) {
 735      boundError = true;
 736    });
 737    var result = model.set({a: 100}, {validate:true});
 738    equal(result, model);
 739    equal(model.get('a'), 100);
 740    equal(model.validationError, null);
 741    equal(boundError, undefined);
 742    result = model.set({a: 200, admin: true}, {validate:true});
 743    equal(result, false);
 744    equal(model.get('a'), 100);
 745    equal(model.validationError, "Can't change admin status.");
 746    equal(boundError, true);
 747  });
 748
 749  test("defaults always extend attrs (#459)", 2, function() {
 750    var Defaulted = Backbone.Model.extend({
 751      defaults: {one: 1},
 752      initialize : function(attrs, opts) {
 753        equal(this.attributes.one, 1);
 754      }
 755    });
 756    var providedattrs = new Defaulted({});
 757    var emptyattrs = new Defaulted();
 758  });
 759
 760  test("Inherit class properties", 6, function() {
 761    var Parent = Backbone.Model.extend({
 762      instancePropSame: function() {},
 763      instancePropDiff: function() {}
 764    }, {
 765      classProp: function() {}
 766    });
 767    var Child = Parent.extend({
 768      instancePropDiff: function() {}
 769    });
 770
 771    var adult = new Parent;
 772    var kid   = new Child;
 773
 774    equal(Child.classProp, Parent.classProp);
 775    notEqual(Child.classProp, undefined);
 776
 777    equal(kid.instancePropSame, adult.instancePropSame);
 778    notEqual(kid.instancePropSame, undefined);
 779
 780    notEqual(Child.prototype.instancePropDiff, Parent.prototype.instancePropDiff);
 781    notEqual(Child.prototype.instancePropDiff, undefined);
 782  });
 783
 784  test("Nested change events don't clobber previous attributes", 4, function() {
 785    new Backbone.Model()
 786    .on('change:state', function(model, newState) {
 787      equal(model.previous('state'), undefined);
 788      equal(newState, 'hello');
 789      // Fire a nested change event.
 790      model.set({other: 'whatever'});
 791    })
 792    .on('change:state', function(model, newState) {
 793      equal(model.previous('state'), undefined);
 794      equal(newState, 'hello');
 795    })
 796    .set({state: 'hello'});
 797  });
 798
 799  test("hasChanged/set should use same comparison", 2, function() {
 800    var changed = 0, model = new Backbone.Model({a: null});
 801    model.on('change', function() {
 802      ok(this.hasChanged('a'));
 803    })
 804    .on('change:a', function() {
 805      changed++;
 806    })
 807    .set({a: undefined});
 808    equal(changed, 1);
 809  });
 810
 811  test("#582, #425, change:attribute callbacks should fire after all changes have occurred", 9, function() {
 812    var model = new Backbone.Model;
 813
 814    var assertion = function() {
 815      equal(model.get('a'), 'a');
 816      equal(model.get('b'), 'b');
 817      equal(model.get('c'), 'c');
 818    };
 819
 820    model.on('change:a', assertion);
 821    model.on('change:b', assertion);
 822    model.on('change:c', assertion);
 823
 824    model.set({a: 'a', b: 'b', c: 'c'});
 825  });
 826
 827  test("#871, set with attributes property", 1, function() {
 828    var model = new Backbone.Model();
 829    model.set({attributes: true});
 830    ok(model.has('attributes'));
 831  });
 832
 833  test("set value regardless of equality/change", 1, function() {
 834    var model = new Backbone.Model({x: []});
 835    var a = [];
 836    model.set({x: a});
 837    ok(model.get('x') === a);
 838  });
 839
 840  test("set same value does not trigger change", 0, function() {
 841    var model = new Backbone.Model({x: 1});
 842    model.on('change change:x', function() { ok(false); });
 843    model.set({x: 1});
 844    model.set({x: 1});
 845  });
 846
 847  test("unset does not fire a change for undefined attributes", 0, function() {
 848    var model = new Backbone.Model({x: undefined});
 849    model.on('change:x', function(){ ok(false); });
 850    model.unset('x');
 851  });
 852
 853  test("set: undefined values", 1, function() {
 854    var model = new Backbone.Model({x: undefined});
 855    ok('x' in model.attributes);
 856  });
 857
 858  test("hasChanged works outside of change events, and true within", 6, function() {
 859    var model = new Backbone.Model({x: 1});
 860    model.on('change:x', function() {
 861      ok(model.hasChanged('x'));
 862      equal(model.get('x'), 1);
 863    });
 864    model.set({x: 2}, {silent: true});
 865    ok(model.hasChanged());
 866    equal(model.hasChanged('x'), true);
 867    model.set({x: 1});
 868    ok(model.hasChanged());
 869    equal(model.hasChanged('x'), true);
 870  });
 871
 872  test("hasChanged gets cleared on the following set", 4, function() {
 873    var model = new Backbone.Model;
 874    model.set({x: 1});
 875    ok(model.hasChanged());
 876    model.set({x: 1});
 877    ok(!model.hasChanged());
 878    model.set({x: 2});
 879    ok(model.hasChanged());
 880    model.set({});
 881    ok(!model.hasChanged());
 882  });
 883
 884  test("save with `wait` succeeds without `validate`", 1, function() {
 885    var model = new Backbone.Model();
 886    model.url = '/test';
 887    model.save({x: 1}, {wait: true});
 888    ok(this.syncArgs.model === model);
 889  });
 890
 891  test("save without `wait` doesn't set invalid attributes", function () {
 892    var model = new Backbone.Model();
 893    model.validate = function () { return 1; }
 894    model.save({a: 1});
 895    equal(model.get('a'), void 0);
 896  });
 897
 898  test("save doesn't validate twice", function () {
 899    var model = new Backbone.Model();
 900    var times = 0;
 901    model.sync = function () {};
 902    model.validate = function () { ++times; }
 903    model.save({});
 904    equal(times, 1);
 905  });
 906
 907  test("`hasChanged` for falsey keys", 2, function() {
 908    var model = new Backbone.Model();
 909    model.set({x: true}, {silent: true});
 910    ok(!model.hasChanged(0));
 911    ok(!model.hasChanged(''));
 912  });
 913
 914  test("`previous` for falsey keys", 2, function() {
 915    var model = new Backbone.Model({0: true, '': true});
 916    model.set({0: false, '': false}, {silent: true});
 917    equal(model.previous(0), true);
 918    equal(model.previous(''), true);
 919  });
 920
 921  test("`save` with `wait` sends correct attributes", 5, function() {
 922    var changed = 0;
 923    var model = new Backbone.Model({x: 1, y: 2});
 924    model.url = '/test';
 925    model.on('change:x', function() { changed++; });
 926    model.save({x: 3}, {wait: true});
 927    deepEqual(JSON.parse(this.ajaxSettings.data), {x: 3, y: 2});
 928    equal(model.get('x'), 1);
 929    equal(changed, 0);
 930    this.syncArgs.options.success({});
 931    equal(model.get('x'), 3);
 932    equal(changed, 1);
 933  });
 934
 935  test("a failed `save` with `wait` doesn't leave attributes behind", 1, function() {
 936    var model = new Backbone.Model;
 937    model.url = '/test';
 938    model.save({x: 1}, {wait: true});
 939    equal(model.get('x'), void 0);
 940  });
 941
 942  test("#1030 - `save` with `wait` results in correct attributes if success is called during sync", 2, function() {
 943    var model = new Backbone.Model({x: 1, y: 2});
 944    model.sync = function(method, model, options) {
 945      options.success();
 946    };
 947    model.on("change:x", function() { ok(true); });
 948    model.save({x: 3}, {wait: true});
 949    equal(model.get('x'), 3);
 950  });
 951
 952  test("save with wait validates attributes", function() {
 953    var model = new Backbone.Model();
 954    model.url = '/test';
 955    model.validate = function() { ok(true); };
 956    model.save({x: 1}, {wait: true});
 957  });
 958
 959  test("save turns on parse flag", function () {
 960    var Model = Backbone.Model.extend({
 961      sync: function(method, model, options) { ok(options.parse); }
 962    });
 963    new Model().save();
 964  });
 965
 966  test("nested `set` during `'change:attr'`", 2, function() {
 967    var events = [];
 968    var model = new Backbone.Model();
 969    model.on('all', function(event) { events.push(event); });
 970    model.on('change', function() {
 971      model.set({z: true}, {silent:true});
 972    });
 973    model.on('change:x', function() {
 974      model.set({y: true});
 975    });
 976    model.set({x: true});
 977    deepEqual(events, ['change:y', 'change:x', 'change']);
 978    events = [];
 979    model.set({z: true});
 980    deepEqual(events, []);
 981  });
 982
 983  test("nested `change` only fires once", 1, function() {
 984    var model = new Backbone.Model();
 985    model.on('change', function() {
 986      ok(true);
 987      model.set({x: true});
 988    });
 989    model.set({x: true});
 990  });
 991
 992  test("nested `set` during `'change'`", 6, function() {
 993    var count = 0;
 994    var model = new Backbone.Model();
 995    model.on('change', function() {
 996      switch(count++) {
 997        case 0:
 998          deepEqual(this.changedAttributes(), {x: true});
 999          equal(model.previous('x'), undefined);
1000          model.set({y: true});
1001          break;
1002        case 1:
1003          deepEqual(this.changedAttributes(), {x: true, y: true});
1004          equal(model.previous('x'), undefined);
1005          model.set({z: true});
1006          break;
1007        case 2:
1008          deepEqual(this.changedAttributes(), {x: true, y: true, z: true});
1009          equal(model.previous('y'), undefined);
1010          break;
1011        default:
1012          ok(false);
1013      }
1014    });
1015    model.set({x: true});
1016  });
1017
1018  test("nested `change` with silent", 3, function() {
1019    var count = 0;
1020    var model = new Backbone.Model();
1021    model.on('change:y', function() { ok(false); });
1022    model.on('change', function() {
1023      switch(count++) {
1024        case 0:
1025          deepEqual(this.changedAttributes(), {x: true});
1026          model.set({y: true}, {silent: true});
1027          model.set({z: true});
1028          break;
1029        case 1:
1030          deepEqual(this.changedAttributes(), {x: true, y: true, z: true});
1031          break;
1032        case 2:
1033          deepEqual(this.changedAttributes(), {z: false});
1034          break;
1035        default:
1036          ok(false);
1037      }
1038    });
1039    model.set({x: true});
1040    model.set({z: false});
1041  });
1042
1043  test("nested `change:attr` with silent", 0, function() {
1044    var model = new Backbone.Model();
1045    model.on('change:y', function(){ ok(false); });
1046    model.on('change', function() {
1047      model.set({y: true}, {silent: true});
1048      model.set({z: true});
1049    });
1050    model.set({x: true});
1051  });
1052
1053  test("multiple nested changes with silent", 1, function() {
1054    var model = new Backbone.Model();
1055    model.on('change:x', function() {
1056      model.set({y: 1}, {silent: true});
1057      model.set({y: 2});
1058    });
1059    model.on('change:y', function(model, val) {
1060      equal(val, 2);
1061    });
1062    model.set({x: true});
1063  });
1064
1065  test("multiple nested changes with silent", 1, function() {
1066    var changes = [];
1067    var model = new Backbone.Model();
1068    model.on('change:b', function(model, val) { changes.push(val); });
1069    model.on('change', function() {
1070      model.set({b: 1});
1071    });
1072    model.set({b: 0});
1073    deepEqual(changes, [0, 1]);
1074  });
1075
1076  test("basic silent change semantics", 1, function() {
1077    var model = new Backbone.Model;
1078    model.set({x: 1});
1079    model.on('change', function(){ ok(true); });
1080    model.set({x: 2}, {silent: true});
1081    model.set({x: 1});
1082  });
1083
1084  test("nested set multiple times", 1, function() {
1085    var model = new Backbone.Model();
1086    model.on('change:b', function() {
1087      ok(true);
1088    });
1089    model.on('change:a', function() {
1090      model.set({b: true});
1091      model.set({b: true});
1092    });
1093    model.set({a: true});
1094  });
1095
1096  test("#1122 - clear does not alter options.", 1, function() {
1097    var model = new Backbone.Model();
1098    var options = {};
1099    model.clear(options);
1100    ok(!options.unset);
1101  });
1102
1103  test("#1122 - unset does not alter options.", 1, function() {
1104    var model = new Backbone.Model();
1105    var options = {};
1106    model.unset('x', options);
1107    ok(!options.unset);
1108  });
1109
1110  test("#1355 - `options` is passed to success callbacks", 3, function() {
1111    var model = new Backbone.Model();
1112    var opts = {
1113      success: function( model, resp, options ) {
1114        ok(options);
1115      }
1116    };
1117    model.sync = function(method, model, options) {
1118      options.success();
1119    };
1120    model.save({id: 1}, opts);
1121    model.fetch(opts);
1122    model.destroy(opts);
1123  });
1124
1125  test("#1412 - Trigger 'sync' event.", 3, function() {
1126    var model = new Backbone.Model({id: 1});
1127    model.sync = function (method, model, options) { options.success(); };
1128    model.on('sync', function(){ ok(true); });
1129    model.fetch();
1130    model.save();
1131    model.destroy();
1132  });
1133
1134  asyncTest("#1365 - Destroy: New models execute success callback.", 2, function() {
1135    new Backbone.Model()
1136    .on('sync', function() { ok(false); })
1137    .on('destroy', function(){ ok(true); })
1138    .destroy({ success: function(){
1139        ok(true);
1140        start();
1141    }});
1142  });
1143
1144  test("#1433 - Save: An invalid model cannot be persisted.", 1, function() {
1145    var model = new Backbone.Model;
1146    model.validate = function(){ return 'invalid'; };
1147    model.sync = function(){ ok(false); };
1148    strictEqual(model.save(), false);
1149  });
1150
1151  test("#1377 - Save without attrs triggers 'error'.", 1, function() {
1152    var Model = Backbone.Model.extend({
1153      url: '/test/',
1154      sync: function(method, model, options){ options.success(); },
1155      validate: function(){ return 'invalid'; }
1156    });
1157    var model = new Model({id: 1});
1158    model.on('invalid', function(){ ok(true); });
1159    model.save();
1160  });
1161
1162  test("#1545 - `undefined` can be passed to a model constructor without coersion", function() {
1163    var Model = Backbone.Model.extend({
1164      defaults: { one: 1 },
1165      initialize : function(attrs, opts) {
1166        equal(attrs, undefined);
1167      }
1168    });
1169    var emptyattrs = new Model();
1170    var undefinedattrs = new Model(undefined);
1171  });
1172
1173  asyncTest("#1478 - Model `save` does not trigger change on unchanged attributes", 0, function() {
1174    var Model = Backbone.Model.extend({
1175      sync: function(method, model, options) {
1176        setTimeout(function(){
1177          options.success();
1178          start();
1179        }, 0);
1180      }
1181    });
1182    new Model({x: true})
1183    .on('change:x', function(){ ok(false); })
1184    .save(null, {wait: true});
1185  });
1186
1187  test("#1664 - Changing from one value, silently to another, back to original triggers a change.", 1, function() {
1188    var model = new Backbone.Model({x:1});
1189    model.on('change:x', function() { ok(true); });
1190    model.set({x:2},{silent:true});
1191    model.set({x:3},{silent:true});
1192    model.set({x:1});
1193  });
1194
1195  test("#1664 - multiple silent changes nested inside a change event", 2, function() {
1196    var changes = [];
1197    var model = new Backbone.Model();
1198    model.on('change', function() {
1199      model.set({a:'c'}, {silent:true});
1200      model.set({b:2}, {silent:true});
1201      model.unset('c', {silent:true});
1202    });
1203    model.on('change:a change:b change:c', function(model, val) { changes.push(val); });
1204    model.set({a:'a', b:1, c:'item'});
1205    deepEqual(changes, ['a',1,'item']);
1206    deepEqual(model.attributes, {a: 'c', b: 2});
1207  });
1208
1209  test("#1791 - `attributes` is available for `parse`", function() {
1210    var Model = Backbone.Model.extend({
1211      parse: function() { this.has('a'); } // shouldn't throw an error
1212    });
1213    var model = new Model(null, {parse: true});
1214    expect(0);
1215  });
1216
1217  test("silent changes in last `change` event back to original triggers change", 2, function() {
1218    var changes = [];
1219    var model = new Backbone.Model();
1220    model.on('change:a change:b change:c', function(model, val) { changes.push(val); });
1221    model.on('change', function() {
1222      model.set({a:'c'}, {silent:true});
1223    });
1224    model.set({a:'a'});
1225    deepEqual(changes, ['a']);
1226    model.set({a:'a'});
1227    deepEqual(changes, ['a', 'a']);
1228  });
1229
1230  test("#1943 change calculations should use _.isEqual", function() {
1231    var model = new Backbone.Model({a: {key: 'value'}});
1232    model.set('a', {key:'value'}, {silent:true});
1233    equal(model.changedAttributes(), false);
1234  });
1235
1236  test("#1964 - final `change` event is always fired, regardless of interim changes", 1, function () {
1237    var model = new Backbone.Model();
1238    model.on('change:property', function() {
1239      model.set('property', 'bar');
1240    });
1241    model.on('change', function() {
1242      ok(true);
1243    });
1244    model.set('property', 'foo');
1245  });
1246
1247  test("isValid", function() {
1248    var model = new Backbone.Model({valid: true});
1249    model.validate = function(attrs) {
1250      if (!attrs.valid) return "invalid";
1251    };
1252    equal(model.isValid(), true);
1253    equal(model.set({valid: false}, {validate:true}), false);
1254    equal(model.isValid(), true);
1255    model.set({valid:false});
1256    equal(model.isValid(), false);
1257    ok(!model.set('valid', false, {validate: true}));
1258  });
1259
1260  test("#1179 - isValid returns true in the absence of validate.", 1, function() {
1261    var model = new Backbone.Model();
1262    model.validate = null;
1263    ok(model.isValid());
1264  });
1265
1266  test("#1961 - Creating a model with {validate:true} will call validate and use the error callback", function () {
1267    var Model = Backbone.Model.extend({
1268      validate: function (attrs) {
1269        if (attrs.id === 1) return "This shouldn't happen";
1270      }
1271    });
1272    var model = new Model({id: 1}, {validate: true});
1273    equal(model.validationError, "This shouldn't happen");
1274  });
1275
1276  test("toJSON receives attrs during save(..., {wait: true})", 1, function() {
1277    var Model = Backbone.Model.extend({
1278      url: '/test',
1279      toJSON: function() {
1280        strictEqual(this.attributes.x, 1);
1281        return _.clone(this.attributes);
1282      }
1283    });
1284    var model = new Model;
1285    model.save({x: 1}, {wait: true});
1286  });
1287
1288  test("#2034 - nested set with silent only triggers one change", 1, function() {
1289    var model = new Backbone.Model();
1290    model.on('change', function() {
1291      model.set({b: true}, {silent: true});
1292      ok(true);
1293    });
1294    model.set({a: true});
1295  });
1296
1297})();