Search code examples
unit-testingbackbone.js

Backbone - testing views - how to handle baseview?


I want to test a Backbone.js view. All rather generic view methods (get template, get model data, render HTML) are stored in a baseview most of my views extend.

Question 1: Since the two – the view to test and the baseview - are separated, does this mean I don't need to test a view's render method because baseview's test should cover this? Or should I test every view's render method, even when this falls back to methods defined on the baseview, to test how the two play together?

Question 2: I am not sure how the baseview can be tested in isolation. If another view extends it, a template name needs to be set for the baseview to work. Should I just mock the template or treat this view like an abstract class that can't be tested in isolation?


Solution

  • Disclaimer: testing is an art, I don't think there's an obvious "best" answer here. But here's what I would do:

    1. I would test everything: test the base view and all the inheriting views. After all, how do you know that your inheriting views are sharing the same render method as the base view? As your project evolves, you may find that the views you inherit from change—but you probably want to make sure that all your views always render!

    2. I would test the base view as its own instantiated object, even if that's not how you're using it in your application. If a template needs to be set for the base view to work, set a template! I don't think you need to "mock" the template—perhaps you can just use underscore's _.template function?