As part of my unit tests (using QUnit) for a backbone project, I test some collection manipulation functions that return arrays of backbone models.
Is there a way to directly test (for sanity's sake) whether the objects in my array extend Backbone.Model or should I just do a duck type check (and if so, how, and on which unique attribute, for example)?
Since there is no real "Class" construct in javascript, typeof
obviously won't do the trick here.
I could see this being useful in other tests down the road for my Collections, or to check that things are instances of my specific Backbone classes, etc.
How about using instanceof
:
console.log(yourObject instanceof Backbone.Model);
The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.
A check against an object's type is a code smell in languages like JavaScript.
If you need to know that your collection is returning a specific model when calling a specific method, populate the collection with known models and make the comparison against those models.
MyModel = Backbone.Model.extend({}); MyCollection = Backbone.Collection.extend({ model: MyModel, getThatOne: function(){ return this.at[0]; } }); m1 = new MyModel(); m2 = new MyModel(); col = new MyCollection([m1, m2]); retrieved = col.getThatOne(); retrieved === m1 //=> true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With