Quantcast
Channel: Dumitru Glavan » javascript
Viewing all articles
Browse latest Browse all 10

Test parent function calls with Jasmine for Backbone.js and write getters with CoffeeScript

$
0
0

I spent about half an hour figuring out how to test a parent function call with Jasmine on code written with CoffeeScript. And, as usual, it was a stupid mistake.

So, my intension was to rewrite the “get” method of a Backbone Model class that will return a custom attribute. The code in CoffeeScript looks like this:

class Person extends Backbone.Model
  default:
    name:    null
    surname: null
    
  get: (attribute)->
    switch attribute
      when 'fullname' then @getFullname()
      else super attribute

  getFullname: ()->
    "#{@get('name')} #{@get('surname')}"

The model’s core “get” is rewritten here and checks the attribute calls. If the attribute equals “fullname” – the code will return the result of the “getFullname” method of the class. This method will glue the name and surname of the person that are stored as object’s attributes. In all other cases the parent “get” function will be called.

The specs for this code is pretty simple. The ambiguous thing is to spec the CoffeeScript “super” call on “get” method. In CoffeeScript the “super” keyword accesses the prototype of the class. The easiest way to test it is like this:

describe "Person", ()->
  person = undefined
  
  beforeEach ()->
    person = new window.Person()

  describe "get", ()->
    describe "when the full name is requested", ()->
      it "gets the full name", ()->
        spyOn(person, 'getFullname')
        person.get('fullname')
        expect(person.getFullname).toHaveBeenCalled()

    describe "when another attribute is requested", ()->
      it "calls super", ()->
        spyOn(window.Backbone.Model.prototype, 'get')
        person.get('fakeAttribute')
        expect(window.Backbone.Model.prototype.get)
        .toHaveBeenCalledWith('fakeAttribute')

  describe "getFullname", ()->
    ...

In the second describe block we check if the the call arrives to the parent class. That’s a pretty easy but sometimes confusing thing to do. The confusion comes from CoffeeScript that makes you forget that the “super” keyword translates as a prototype call :)


Viewing all articles
Browse latest Browse all 10

Trending Articles