B Robster
B Robster

Reputation: 42053

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

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.

Upvotes: 21

Views: 7085

Answers (2)

Derick Bailey
Derick Bailey

Reputation: 72868

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

Upvotes: 3

Sarfraz
Sarfraz

Reputation: 382726

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.

Upvotes: 37

Related Questions