PageRenderTime 91ms CodeModel.GetById 15ms app.highlight 67ms RepoModel.GetById 1ms app.codeStats 1ms

/test/model.js

https://github.com/1998763/backbone
JavaScript | 1135 lines | 1015 code | 119 blank | 1 comment | 15 complexity | faafb806e620f909bf5e19c4d2166b15 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    raises(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("set and unset", 8, function() {
 208    var a = new Backbone.Model({id: 'id', foo: 1, bar: 2, baz: 3});
 209    var changeCount = 0;
 210    a.on("change:foo", function() { changeCount += 1; });
 211    a.set({'foo': 2});
 212    ok(a.get('foo') == 2, "Foo should have changed.");
 213    ok(changeCount == 1, "Change count should have incremented.");
 214    a.set({'foo': 2}); // set with value that is not new shouldn't fire change event
 215    ok(a.get('foo') == 2, "Foo should NOT have changed, still 2");
 216    ok(changeCount == 1, "Change count should NOT have incremented.");
 217
 218    a.validate = function(attrs) {
 219      equal(attrs.foo, void 0, "validate:true passed while unsetting");
 220    };
 221    a.unset('foo', {validate: true});
 222    equal(a.get('foo'), void 0, "Foo should have changed");
 223    delete a.validate;
 224    ok(changeCount == 2, "Change count should have incremented for unset.");
 225
 226    a.unset('id');
 227    equal(a.id, undefined, "Unsetting the id should remove the id property.");
 228  });
 229
 230  test("#2030 - set with failed validate, followed by another set triggers change", function () {
 231    var attr = 0, main = 0, error = 0;
 232    var Model = Backbone.Model.extend({
 233      validate: function (attr) {
 234        if (attr.x > 1) {
 235          error++;
 236          return "this is an error";
 237        }
 238      }
 239    });
 240    var model = new Model({x:0});
 241      model.on('change:x', function () { attr++; });
 242      model.on('change', function () { main++; });
 243      model.set({x:2}, {validate:true});
 244      model.set({x:1}, {validate:true});
 245      deepEqual([attr, main, error], [1, 1, 1]);
 246  });
 247
 248  test("set triggers changes in the correct order", function() {
 249    var value = null;
 250    var model = new Backbone.Model;
 251    model.on('last', function(){ value = 'last'; });
 252    model.on('first', function(){ value = 'first'; });
 253    model.trigger('first');
 254    model.trigger('last');
 255    equal(value, 'last');
 256  });
 257
 258  test("set falsy values in the correct order", 2, function() {
 259    var model = new Backbone.Model({result: 'result'});
 260    model.on('change', function() {
 261      equal(model.changed.result, void 0);
 262      equal(model.previous('result'), false);
 263    });
 264    model.set({result: void 0}, {silent: true});
 265    model.set({result: null}, {silent: true});
 266    model.set({result: false}, {silent: true});
 267    model.set({result: void 0});
 268  });
 269
 270  test("nested set triggers with the correct options", function() {
 271    var model = new Backbone.Model();
 272    var o1 = {};
 273    var o2 = {};
 274    var o3 = {};
 275    model.on('change', function(__, options) {
 276      switch (model.get('a')) {
 277      case 1:
 278        equal(options, o1);
 279        return model.set('a', 2, o2);
 280      case 2:
 281        equal(options, o2);
 282        return model.set('a', 3, o3);
 283      case 3:
 284        equal(options, o3);
 285      }
 286    });
 287    model.set('a', 1, o1);
 288  });
 289
 290  test("multiple unsets", 1, function() {
 291    var i = 0;
 292    var counter = function(){ i++; };
 293    var model = new Backbone.Model({a: 1});
 294    model.on("change:a", counter);
 295    model.set({a: 2});
 296    model.unset('a');
 297    model.unset('a');
 298    equal(i, 2, 'Unset does not fire an event for missing attributes.');
 299  });
 300
 301  test("unset and changedAttributes", 1, function() {
 302    var model = new Backbone.Model({a: 1});
 303    model.on('change', function() {
 304      ok('a' in model.changedAttributes(), 'changedAttributes should contain unset properties');
 305    });
 306    model.unset('a');
 307  });
 308
 309  test("using a non-default id attribute.", 5, function() {
 310    var MongoModel = Backbone.Model.extend({idAttribute : '_id'});
 311    var model = new MongoModel({id: 'eye-dee', _id: 25, title: 'Model'});
 312    equal(model.get('id'), 'eye-dee');
 313    equal(model.id, 25);
 314    equal(model.isNew(), false);
 315    model.unset('_id');
 316    equal(model.id, undefined);
 317    equal(model.isNew(), true);
 318  });
 319
 320  test("set an empty string", 1, function() {
 321    var model = new Backbone.Model({name : "Model"});
 322    model.set({name : ''});
 323    equal(model.get('name'), '');
 324  });
 325
 326  test("setting an object", 1, function() {
 327    var model = new Backbone.Model({
 328      custom: { foo: 1 }
 329    });
 330    model.on('change', function() {
 331      ok(1);
 332    });
 333    model.set({
 334      custom: { foo: 1 } // no change should be fired
 335    });
 336    model.set({
 337      custom: { foo: 2 } // change event should be fired
 338    });
 339  });
 340
 341  test("clear", 3, function() {
 342    var changed;
 343    var model = new Backbone.Model({id: 1, name : "Model"});
 344    model.on("change:name", function(){ changed = true; });
 345    model.on("change", function() {
 346      var changedAttrs = model.changedAttributes();
 347      ok('name' in changedAttrs);
 348    });
 349    model.clear();
 350    equal(changed, true);
 351    equal(model.get('name'), undefined);
 352  });
 353
 354  test("defaults", 4, function() {
 355    var Defaulted = Backbone.Model.extend({
 356      defaults: {
 357        "one": 1,
 358        "two": 2
 359      }
 360    });
 361    var model = new Defaulted({two: undefined});
 362    equal(model.get('one'), 1);
 363    equal(model.get('two'), 2);
 364    Defaulted = Backbone.Model.extend({
 365      defaults: function() {
 366        return {
 367          "one": 3,
 368          "two": 4
 369        };
 370      }
 371    });
 372    model = new Defaulted({two: undefined});
 373    equal(model.get('one'), 3);
 374    equal(model.get('two'), 4);
 375  });
 376
 377  test("change, hasChanged, changedAttributes, previous, previousAttributes", 9, function() {
 378    var model = new Backbone.Model({name: "Tim", age: 10});
 379    deepEqual(model.changedAttributes(), false);
 380    model.on('change', function() {
 381      ok(model.hasChanged('name'), 'name changed');
 382      ok(!model.hasChanged('age'), 'age did not');
 383      ok(_.isEqual(model.changedAttributes(), {name : 'Rob'}), 'changedAttributes returns the changed attrs');
 384      equal(model.previous('name'), 'Tim');
 385      ok(_.isEqual(model.previousAttributes(), {name : "Tim", age : 10}), 'previousAttributes is correct');
 386    });
 387    equal(model.hasChanged(), false);
 388    equal(model.hasChanged(undefined), false);
 389    model.set({name : 'Rob'});
 390    equal(model.get('name'), 'Rob');
 391  });
 392
 393  test("changedAttributes", 3, function() {
 394    var model = new Backbone.Model({a: 'a', b: 'b'});
 395    deepEqual(model.changedAttributes(), false);
 396    equal(model.changedAttributes({a: 'a'}), false);
 397    equal(model.changedAttributes({a: 'b'}).a, 'b');
 398  });
 399
 400  test("change with options", 2, function() {
 401    var value;
 402    var model = new Backbone.Model({name: 'Rob'});
 403    model.on('change', function(model, options) {
 404      value = options.prefix + model.get('name');
 405    });
 406    model.set({name: 'Bob'}, {prefix: 'Mr. '});
 407    equal(value, 'Mr. Bob');
 408    model.set({name: 'Sue'}, {prefix: 'Ms. '});
 409    equal(value, 'Ms. Sue');
 410  });
 411
 412  test("change after initialize", 1, function () {
 413    var changed = 0;
 414    var attrs = {id: 1, label: 'c'};
 415    var obj = new Backbone.Model(attrs);
 416    obj.on('change', function() { changed += 1; });
 417    obj.set(attrs);
 418    equal(changed, 0);
 419  });
 420
 421  test("save within change event", 1, function () {
 422    var env = this;
 423    var model = new Backbone.Model({firstName : "Taylor", lastName: "Swift"});
 424    model.url = '/test';
 425    model.on('change', function () {
 426      model.save();
 427      ok(_.isEqual(env.syncArgs.model, model));
 428    });
 429    model.set({lastName: 'Hicks'});
 430  });
 431
 432  test("validate after save", 2, function() {
 433    var lastError, model = new Backbone.Model();
 434    model.validate = function(attrs) {
 435      if (attrs.admin) return "Can't change admin status.";
 436    };
 437    model.sync = function(method, model, options) {
 438      options.success.call(this, {admin: true});
 439    };
 440    model.on('invalid', function(model, error) {
 441      lastError = error;
 442    });
 443    model.save(null);
 444
 445    equal(lastError, "Can't change admin status.");
 446    equal(model.validationError, "Can't change admin status.");
 447  });
 448
 449  test("save", 2, function() {
 450    doc.save({title : "Henry V"});
 451    equal(this.syncArgs.method, 'update');
 452    ok(_.isEqual(this.syncArgs.model, doc));
 453  });
 454
 455  test("save, fetch, destroy triggers error event when an error occurs", 3, function () {
 456    var model = new Backbone.Model();
 457    model.on('error', function () {
 458      ok(true);
 459    });
 460    model.sync = function (method, model, options) {
 461      options.error();
 462    };
 463    model.save({data: 2, id: 1});
 464    model.fetch();
 465    model.destroy();
 466  });
 467
 468  test("save with PATCH", function() {
 469    doc.clear().set({id: 1, a: 1, b: 2, c: 3, d: 4});
 470    doc.save();
 471    equal(this.syncArgs.method, 'update');
 472    equal(this.syncArgs.options.attrs, undefined);
 473
 474    doc.save({b: 2, d: 4}, {patch: true});
 475    equal(this.syncArgs.method, 'patch');
 476    equal(_.size(this.syncArgs.options.attrs), 2);
 477    equal(this.syncArgs.options.attrs.d, 4);
 478    equal(this.syncArgs.options.attrs.a, undefined);
 479    equal(this.ajaxSettings.data, "{\"b\":2,\"d\":4}");
 480  });
 481
 482  test("save in positional style", 1, function() {
 483    var model = new Backbone.Model();
 484    model.sync = function(method, model, options) {
 485      options.success();
 486    };
 487    model.save('title', 'Twelfth Night');
 488    equal(model.get('title'), 'Twelfth Night');
 489  });
 490
 491  test("save with non-object success response", 2, function () {
 492    var model = new Backbone.Model();
 493    model.sync = function(method, model, options) {
 494      options.success('', options);
 495      options.success(null, options);
 496    };
 497    model.save({testing:'empty'}, {
 498      success: function (model) {
 499        deepEqual(model.attributes, {testing:'empty'});
 500      }
 501    });
 502  });
 503
 504  test("fetch", 2, function() {
 505    doc.fetch();
 506    equal(this.syncArgs.method, 'read');
 507    ok(_.isEqual(this.syncArgs.model, doc));
 508  });
 509
 510  test("destroy", 3, function() {
 511    doc.destroy();
 512    equal(this.syncArgs.method, 'delete');
 513    ok(_.isEqual(this.syncArgs.model, doc));
 514
 515    var newModel = new Backbone.Model;
 516    equal(newModel.destroy(), false);
 517  });
 518
 519  test("non-persisted destroy", 1, function() {
 520    var a = new Backbone.Model({ 'foo': 1, 'bar': 2, 'baz': 3});
 521    a.sync = function() { throw "should not be called"; };
 522    a.destroy();
 523    ok(true, "non-persisted model should not call sync");
 524  });
 525
 526  test("validate", function() {
 527    var lastError;
 528    var model = new Backbone.Model();
 529    model.validate = function(attrs) {
 530      if (attrs.admin != this.get('admin')) return "Can't change admin status.";
 531    };
 532    model.on('invalid', function(model, error) {
 533      lastError = error;
 534    });
 535    var result = model.set({a: 100});
 536    equal(result, model);
 537    equal(model.get('a'), 100);
 538    equal(lastError, undefined);
 539    result = model.set({admin: true});
 540    equal(model.get('admin'), true);
 541    result = model.set({a: 200, admin: false}, {validate:true});
 542    equal(lastError, "Can't change admin status.");
 543    equal(result, false);
 544    equal(model.get('a'), 100);
 545  });
 546
 547  test("validate on unset and clear", 6, function() {
 548    var error;
 549    var model = new Backbone.Model({name: "One"});
 550    model.validate = function(attrs) {
 551      if (!attrs.name) {
 552        error = true;
 553        return "No thanks.";
 554      }
 555    };
 556    model.set({name: "Two"});
 557    equal(model.get('name'), 'Two');
 558    equal(error, undefined);
 559    model.unset('name', {validate: true});
 560    equal(error, true);
 561    equal(model.get('name'), 'Two');
 562    model.clear({validate:true});
 563    equal(model.get('name'), 'Two');
 564    delete model.validate;
 565    model.clear();
 566    equal(model.get('name'), undefined);
 567  });
 568
 569  test("validate with error callback", 8, function() {
 570    var lastError, boundError;
 571    var model = new Backbone.Model();
 572    model.validate = function(attrs) {
 573      if (attrs.admin) return "Can't change admin status.";
 574    };
 575    model.on('invalid', function(model, error) {
 576      boundError = true;
 577    });
 578    var result = model.set({a: 100}, {validate:true});
 579    equal(result, model);
 580    equal(model.get('a'), 100);
 581    equal(model.validationError, null);
 582    equal(boundError, undefined);
 583    result = model.set({a: 200, admin: true}, {validate:true});
 584    equal(result, false);
 585    equal(model.get('a'), 100);
 586    equal(model.validationError, "Can't change admin status.");
 587    equal(boundError, true);
 588  });
 589
 590  test("defaults always extend attrs (#459)", 2, function() {
 591    var Defaulted = Backbone.Model.extend({
 592      defaults: {one: 1},
 593      initialize : function(attrs, opts) {
 594        equal(this.attributes.one, 1);
 595      }
 596    });
 597    var providedattrs = new Defaulted({});
 598    var emptyattrs = new Defaulted();
 599  });
 600
 601  test("Inherit class properties", 6, function() {
 602    var Parent = Backbone.Model.extend({
 603      instancePropSame: function() {},
 604      instancePropDiff: function() {}
 605    }, {
 606      classProp: function() {}
 607    });
 608    var Child = Parent.extend({
 609      instancePropDiff: function() {}
 610    });
 611
 612    var adult = new Parent;
 613    var kid   = new Child;
 614
 615    equal(Child.classProp, Parent.classProp);
 616    notEqual(Child.classProp, undefined);
 617
 618    equal(kid.instancePropSame, adult.instancePropSame);
 619    notEqual(kid.instancePropSame, undefined);
 620
 621    notEqual(Child.prototype.instancePropDiff, Parent.prototype.instancePropDiff);
 622    notEqual(Child.prototype.instancePropDiff, undefined);
 623  });
 624
 625  test("Nested change events don't clobber previous attributes", 4, function() {
 626    new Backbone.Model()
 627    .on('change:state', function(model, newState) {
 628      equal(model.previous('state'), undefined);
 629      equal(newState, 'hello');
 630      // Fire a nested change event.
 631      model.set({other: 'whatever'});
 632    })
 633    .on('change:state', function(model, newState) {
 634      equal(model.previous('state'), undefined);
 635      equal(newState, 'hello');
 636    })
 637    .set({state: 'hello'});
 638  });
 639
 640  test("hasChanged/set should use same comparison", 2, function() {
 641    var changed = 0, model = new Backbone.Model({a: null});
 642    model.on('change', function() {
 643      ok(this.hasChanged('a'));
 644    })
 645    .on('change:a', function() {
 646      changed++;
 647    })
 648    .set({a: undefined});
 649    equal(changed, 1);
 650  });
 651
 652  test("#582, #425, change:attribute callbacks should fire after all changes have occurred", 9, function() {
 653    var model = new Backbone.Model;
 654
 655    var assertion = function() {
 656      equal(model.get('a'), 'a');
 657      equal(model.get('b'), 'b');
 658      equal(model.get('c'), 'c');
 659    };
 660
 661    model.on('change:a', assertion);
 662    model.on('change:b', assertion);
 663    model.on('change:c', assertion);
 664
 665    model.set({a: 'a', b: 'b', c: 'c'});
 666  });
 667
 668  test("#871, set with attributes property", 1, function() {
 669    var model = new Backbone.Model();
 670    model.set({attributes: true});
 671    ok(model.has('attributes'));
 672  });
 673
 674  test("set value regardless of equality/change", 1, function() {
 675    var model = new Backbone.Model({x: []});
 676    var a = [];
 677    model.set({x: a});
 678    ok(model.get('x') === a);
 679  });
 680
 681  test("set same value does not trigger change", 0, function() {
 682    var model = new Backbone.Model({x: 1});
 683    model.on('change change:x', function() { ok(false); });
 684    model.set({x: 1});
 685    model.set({x: 1});
 686  });
 687
 688  test("unset does not fire a change for undefined attributes", 0, function() {
 689    var model = new Backbone.Model({x: undefined});
 690    model.on('change:x', function(){ ok(false); });
 691    model.unset('x');
 692  });
 693
 694  test("set: undefined values", 1, function() {
 695    var model = new Backbone.Model({x: undefined});
 696    ok('x' in model.attributes);
 697  });
 698
 699  test("hasChanged works outside of change events, and true within", 6, function() {
 700    var model = new Backbone.Model({x: 1});
 701    model.on('change:x', function() {
 702      ok(model.hasChanged('x'));
 703      equal(model.get('x'), 1);
 704    });
 705    model.set({x: 2}, {silent: true});
 706    ok(model.hasChanged());
 707    equal(model.hasChanged('x'), true);
 708    model.set({x: 1});
 709    ok(model.hasChanged());
 710    equal(model.hasChanged('x'), true);
 711  });
 712
 713  test("hasChanged gets cleared on the following set", 4, function() {
 714    var model = new Backbone.Model;
 715    model.set({x: 1});
 716    ok(model.hasChanged());
 717    model.set({x: 1});
 718    ok(!model.hasChanged());
 719    model.set({x: 2});
 720    ok(model.hasChanged());
 721    model.set({});
 722    ok(!model.hasChanged());
 723  });
 724
 725  test("save with `wait` succeeds without `validate`", 1, function() {
 726    var model = new Backbone.Model();
 727    model.url = '/test';
 728    model.save({x: 1}, {wait: true});
 729    ok(this.syncArgs.model === model);
 730  });
 731
 732  test("save without `wait` doesn't set invalid attributes", function () {
 733    var model = new Backbone.Model();
 734    model.validate = function () { return 1; }
 735    model.save({a: 1});
 736    equal(model.get('a'), void 0);
 737  });
 738
 739  test("save doesn't validate twice", function () {
 740    var model = new Backbone.Model();
 741    var times = 0;
 742    model.sync = function () {};
 743    model.validate = function () { ++times; }
 744    model.save({});
 745    equal(times, 1);
 746  });
 747
 748  test("`hasChanged` for falsey keys", 2, function() {
 749    var model = new Backbone.Model();
 750    model.set({x: true}, {silent: true});
 751    ok(!model.hasChanged(0));
 752    ok(!model.hasChanged(''));
 753  });
 754
 755  test("`previous` for falsey keys", 2, function() {
 756    var model = new Backbone.Model({0: true, '': true});
 757    model.set({0: false, '': false}, {silent: true});
 758    equal(model.previous(0), true);
 759    equal(model.previous(''), true);
 760  });
 761
 762  test("`save` with `wait` sends correct attributes", 5, function() {
 763    var changed = 0;
 764    var model = new Backbone.Model({x: 1, y: 2});
 765    model.url = '/test';
 766    model.on('change:x', function() { changed++; });
 767    model.save({x: 3}, {wait: true});
 768    deepEqual(JSON.parse(this.ajaxSettings.data), {x: 3, y: 2});
 769    equal(model.get('x'), 1);
 770    equal(changed, 0);
 771    this.syncArgs.options.success({});
 772    equal(model.get('x'), 3);
 773    equal(changed, 1);
 774  });
 775
 776  test("a failed `save` with `wait` doesn't leave attributes behind", 1, function() {
 777    var model = new Backbone.Model;
 778    model.url = '/test';
 779    model.save({x: 1}, {wait: true});
 780    equal(model.get('x'), void 0);
 781  });
 782
 783  test("#1030 - `save` with `wait` results in correct attributes if success is called during sync", 2, function() {
 784    var model = new Backbone.Model({x: 1, y: 2});
 785    model.sync = function(method, model, options) {
 786      options.success();
 787    };
 788    model.on("change:x", function() { ok(true); });
 789    model.save({x: 3}, {wait: true});
 790    equal(model.get('x'), 3);
 791  });
 792
 793  test("save with wait validates attributes", function() {
 794    var model = new Backbone.Model();
 795    model.url = '/test';
 796    model.validate = function() { ok(true); };
 797    model.save({x: 1}, {wait: true});
 798  });
 799
 800  test("save turns on parse flag", function () {
 801    var Model = Backbone.Model.extend({
 802      sync: function(method, model, options) { ok(options.parse); }
 803    });
 804    new Model().save();
 805  });
 806
 807  test("nested `set` during `'change:attr'`", 2, function() {
 808    var events = [];
 809    var model = new Backbone.Model();
 810    model.on('all', function(event) { events.push(event); });
 811    model.on('change', function() {
 812      model.set({z: true}, {silent:true});
 813    });
 814    model.on('change:x', function() {
 815      model.set({y: true});
 816    });
 817    model.set({x: true});
 818    deepEqual(events, ['change:y', 'change:x', 'change']);
 819    events = [];
 820    model.set({z: true});
 821    deepEqual(events, []);
 822  });
 823
 824  test("nested `change` only fires once", 1, function() {
 825    var model = new Backbone.Model();
 826    model.on('change', function() {
 827      ok(true);
 828      model.set({x: true});
 829    });
 830    model.set({x: true});
 831  });
 832
 833  test("nested `set` during `'change'`", 6, function() {
 834    var count = 0;
 835    var model = new Backbone.Model();
 836    model.on('change', function() {
 837      switch(count++) {
 838        case 0:
 839          deepEqual(this.changedAttributes(), {x: true});
 840          equal(model.previous('x'), undefined);
 841          model.set({y: true});
 842          break;
 843        case 1:
 844          deepEqual(this.changedAttributes(), {x: true, y: true});
 845          equal(model.previous('x'), undefined);
 846          model.set({z: true});
 847          break;
 848        case 2:
 849          deepEqual(this.changedAttributes(), {x: true, y: true, z: true});
 850          equal(model.previous('y'), undefined);
 851          break;
 852        default:
 853          ok(false);
 854      }
 855    });
 856    model.set({x: true});
 857  });
 858
 859  test("nested `change` with silent", 3, function() {
 860    var count = 0;
 861    var model = new Backbone.Model();
 862    model.on('change:y', function() { ok(false); });
 863    model.on('change', function() {
 864      switch(count++) {
 865        case 0:
 866          deepEqual(this.changedAttributes(), {x: true});
 867          model.set({y: true}, {silent: true});
 868          model.set({z: true});
 869          break;
 870        case 1:
 871          deepEqual(this.changedAttributes(), {x: true, y: true, z: true});
 872          break;
 873        case 2:
 874          deepEqual(this.changedAttributes(), {z: false});
 875          break;
 876        default:
 877          ok(false);
 878      }
 879    });
 880    model.set({x: true});
 881    model.set({z: false});
 882  });
 883
 884  test("nested `change:attr` with silent", 0, function() {
 885    var model = new Backbone.Model();
 886    model.on('change:y', function(){ ok(false); });
 887    model.on('change', function() {
 888      model.set({y: true}, {silent: true});
 889      model.set({z: true});
 890    });
 891    model.set({x: true});
 892  });
 893
 894  test("multiple nested changes with silent", 1, function() {
 895    var model = new Backbone.Model();
 896    model.on('change:x', function() {
 897      model.set({y: 1}, {silent: true});
 898      model.set({y: 2});
 899    });
 900    model.on('change:y', function(model, val) {
 901      equal(val, 2);
 902    });
 903    model.set({x: true});
 904  });
 905
 906  test("multiple nested changes with silent", 1, function() {
 907    var changes = [];
 908    var model = new Backbone.Model();
 909    model.on('change:b', function(model, val) { changes.push(val); });
 910    model.on('change', function() {
 911      model.set({b: 1});
 912    });
 913    model.set({b: 0});
 914    deepEqual(changes, [0, 1]);
 915  });
 916
 917  test("basic silent change semantics", 1, function() {
 918    var model = new Backbone.Model;
 919    model.set({x: 1});
 920    model.on('change', function(){ ok(true); });
 921    model.set({x: 2}, {silent: true});
 922    model.set({x: 1});
 923  });
 924
 925  test("nested set multiple times", 1, function() {
 926    var model = new Backbone.Model();
 927    model.on('change:b', function() {
 928      ok(true);
 929    });
 930    model.on('change:a', function() {
 931      model.set({b: true});
 932      model.set({b: true});
 933    });
 934    model.set({a: true});
 935  });
 936
 937  test("#1122 - clear does not alter options.", 1, function() {
 938    var model = new Backbone.Model();
 939    var options = {};
 940    model.clear(options);
 941    ok(!options.unset);
 942  });
 943
 944  test("#1122 - unset does not alter options.", 1, function() {
 945    var model = new Backbone.Model();
 946    var options = {};
 947    model.unset('x', options);
 948    ok(!options.unset);
 949  });
 950
 951  test("#1355 - `options` is passed to success callbacks", 3, function() {
 952    var model = new Backbone.Model();
 953    var opts = {
 954      success: function( model, resp, options ) {
 955        ok(options);
 956      }
 957    };
 958    model.sync = function(method, model, options) {
 959      options.success();
 960    };
 961    model.save({id: 1}, opts);
 962    model.fetch(opts);
 963    model.destroy(opts);
 964  });
 965
 966  test("#1412 - Trigger 'sync' event.", 3, function() {
 967    var model = new Backbone.Model({id: 1});
 968    model.sync = function (method, model, options) { options.success(); };
 969    model.on('sync', function(){ ok(true); });
 970    model.fetch();
 971    model.save();
 972    model.destroy();
 973  });
 974
 975  test("#1365 - Destroy: New models execute success callback.", 2, function() {
 976    new Backbone.Model()
 977    .on('sync', function() { ok(false); })
 978    .on('destroy', function(){ ok(true); })
 979    .destroy({ success: function(){ ok(true); }});
 980  });
 981
 982  test("#1433 - Save: An invalid model cannot be persisted.", 1, function() {
 983    var model = new Backbone.Model;
 984    model.validate = function(){ return 'invalid'; };
 985    model.sync = function(){ ok(false); };
 986    strictEqual(model.save(), false);
 987  });
 988
 989  test("#1377 - Save without attrs triggers 'error'.", 1, function() {
 990    var Model = Backbone.Model.extend({
 991      url: '/test/',
 992      sync: function(method, model, options){ options.success(); },
 993      validate: function(){ return 'invalid'; }
 994    });
 995    var model = new Model({id: 1});
 996    model.on('invalid', function(){ ok(true); });
 997    model.save();
 998  });
 999
1000  test("#1545 - `undefined` can be passed to a model constructor without coersion", function() {
1001    var Model = Backbone.Model.extend({
1002      defaults: { one: 1 },
1003      initialize : function(attrs, opts) {
1004        equal(attrs, undefined);
1005      }
1006    });
1007    var emptyattrs = new Model();
1008    var undefinedattrs = new Model(undefined);
1009  });
1010
1011  asyncTest("#1478 - Model `save` does not trigger change on unchanged attributes", 0, function() {
1012    var Model = Backbone.Model.extend({
1013      sync: function(method, model, options) {
1014        setTimeout(function(){
1015          options.success();
1016          start();
1017        }, 0);
1018      }
1019    });
1020    new Model({x: true})
1021    .on('change:x', function(){ ok(false); })
1022    .save(null, {wait: true});
1023  });
1024
1025  test("#1664 - Changing from one value, silently to another, back to original triggers a change.", 1, function() {
1026    var model = new Backbone.Model({x:1});
1027    model.on('change:x', function() { ok(true); });
1028    model.set({x:2},{silent:true});
1029    model.set({x:3},{silent:true});
1030    model.set({x:1});
1031  });
1032
1033  test("#1664 - multiple silent changes nested inside a change event", 2, function() {
1034    var changes = [];
1035    var model = new Backbone.Model();
1036    model.on('change', function() {
1037      model.set({a:'c'}, {silent:true});
1038      model.set({b:2}, {silent:true});
1039      model.unset('c', {silent:true});
1040    });
1041    model.on('change:a change:b change:c', function(model, val) { changes.push(val); });
1042    model.set({a:'a', b:1, c:'item'});
1043    deepEqual(changes, ['a',1,'item']);
1044    deepEqual(model.attributes, {a: 'c', b: 2});
1045  });
1046
1047  test("#1791 - `attributes` is available for `parse`", function() {
1048    var Model = Backbone.Model.extend({
1049      parse: function() { this.has('a'); } // shouldn't throw an error
1050    });
1051    var model = new Model(null, {parse: true});
1052    expect(0);
1053  });
1054
1055  test("silent changes in last `change` event back to original triggers change", 2, function() {
1056    var changes = [];
1057    var model = new Backbone.Model();
1058    model.on('change:a change:b change:c', function(model, val) { changes.push(val); });
1059    model.on('change', function() {
1060      model.set({a:'c'}, {silent:true});
1061    });
1062    model.set({a:'a'});
1063    deepEqual(changes, ['a']);
1064    model.set({a:'a'});
1065    deepEqual(changes, ['a', 'a']);
1066  });
1067
1068  test("#1943 change calculations should use _.isEqual", function() {
1069    var model = new Backbone.Model({a: {key: 'value'}});
1070    model.set('a', {key:'value'}, {silent:true});
1071    equal(model.changedAttributes(), false);
1072  });
1073
1074  test("#1964 - final `change` event is always fired, regardless of interim changes", 1, function () {
1075    var model = new Backbone.Model();
1076    model.on('change:property', function() {
1077      model.set('property', 'bar');
1078    });
1079    model.on('change', function() {
1080      ok(true);
1081    });
1082    model.set('property', 'foo');
1083  });
1084
1085  test("isValid", function() {
1086    var model = new Backbone.Model({valid: true});
1087    model.validate = function(attrs) {
1088      if (!attrs.valid) return "invalid";
1089    };
1090    equal(model.isValid(), true);
1091    equal(model.set({valid: false}, {validate:true}), false);
1092    equal(model.isValid(), true);
1093    model.set({valid:false});
1094    equal(model.isValid(), false);
1095    ok(!model.set('valid', false, {validate: true}));
1096  });
1097
1098  test("#1179 - isValid returns true in the absence of validate.", 1, function() {
1099    var model = new Backbone.Model();
1100    model.validate = null;
1101    ok(model.isValid());
1102  });
1103
1104  test("#1961 - Creating a model with {validate:true} will call validate and use the error callback", function () {
1105    var Model = Backbone.Model.extend({
1106      validate: function (attrs) {
1107        if (attrs.id === 1) return "This shouldn't happen";
1108      }
1109    });
1110    var model = new Model({id: 1}, {validate: true});
1111    equal(model.validationError, "This shouldn't happen");
1112  });
1113
1114  test("toJSON receives attrs during save(..., {wait: true})", 1, function() {
1115    var Model = Backbone.Model.extend({
1116      url: '/test',
1117      toJSON: function() {
1118        strictEqual(this.attributes.x, 1);
1119        return _.clone(this.attributes);
1120      }
1121    });
1122    var model = new Model;
1123    model.save({x: 1}, {wait: true});
1124  });
1125
1126  test("#2034 - nested set with silent only triggers one change", 1, function() {
1127    var model = new Backbone.Model();
1128    model.on('change', function() {
1129      model.set({b: true}, {silent: true});
1130      ok(true);
1131    });
1132    model.set({a: true});
1133  });
1134
1135})();