Backbone.js Testing Pattern - Describe a View's First Render
While testing my backbone.js views, I’ve come up with a few conventions to keep my tests neatly organized. The first is to have a single describe block to specify what the view looks like when it first renders. This tests the view’s rendering logic and establishes the foundation for the rest of my examples. Here’s a brief example. I have a view which renders a person’s name and adds a CSS class if the person is a minor. Pretty simple. There are three things I’m interested in when testing the first render:
show the name
no CSS class if person is over 18
special CSS class if person is under 18
Here’s the view spec:
12345678910111213141516
describePersonView,->describe"first render",->beforeEach->@model = newPerson(name: 'Joe')@view = newPersonView(model: @model)it"shows the name in an h2",->expect($(@view.render().el).find('h2').text()).toEqual('Joe')it"does not add the 'minor' class to the h2 if person is not a minor",->@model.setage: 18expect($(@view.render().el).find('h2').hasClass('minor')).toBe(false)it"adds the 'minor' class to the h2 if person is a minor",->@model.setage: 17expect($(@view.render().el).find('h2').hasClass('minor')).toBe(true)
If the view logic is complex I may separate the conditions into separate describe blocks, like this:
12345678910111213141516171819202122232425
describePersonView,->describe"first render",->beforeEach->@model = newPerson(name: 'Joe')@view = newPersonView(model: @model)describe"person is not a minor",->beforeEach->@model.setage: 18it"shows the name in an h2",->expect($(@view.render().el).find('h2').text()).toEqual('Joe')it"does not add the 'minor' class to the h2",->expect($(@view.render().el).find('h2').hasClass('minor')).toBe(false)describe"person is a minor",->beforeEach->@model.setage: 17it"shows the name in an h2",->expect($(@view.render().el).find('h2').text()).toEqual('Joe')it"adds the 'minor' class to the h2",->expect($(@view.render().el).find('h2').hasClass('minor')).toBe(true)
With these tests in place, I can start testing the events. Details on that will be in a future post.