PageRenderTime 6ms CodeModel.GetById 5ms app.highlight 77ms RepoModel.GetById 1ms app.codeStats 0ms

/test/model.js

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