Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to test whether an object "is a" Backbone.Model in my unit tests?

Tags:

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.

like image 411
B Robster Avatar asked Jun 02 '12 15:06

B Robster


2 Answers

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.

like image 73
Sarfraz Avatar answered Nov 14 '22 03:11

Sarfraz


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 
like image 26
Derick Bailey Avatar answered Nov 14 '22 03:11

Derick Bailey