Introduction
This post is the first in what I hope becomes a series chronicling my journey from completely untestable code to code that is covered with tests from database to browser. Figuring out where to get started with testing can be tricky, especially when you aren’t used to writing code designed to be testable. However, I’ve gotten my first good foothold, and of all places, it’s in the extremeties: the JavaScript that governs the UI logic in the browser. I think it’s pretty cool, so let’s get right to it!
The Basics
In my everyday work, I use Kendo as the framework that my webpages are built upon and I’m already a huge fan of MVVM just because it lets me write less code and focus on developing the specific logic the page calls for rather than waste time reading and writing to various HTML elements. I just manipulate the ViewModel and let the bindings handle the visual representation. Now imagine if you could develop a ViewModel that you could put into a test harness and confirm that it behaves correctly without even having a UI developed yet. That’s precisely what I’m going to demonstrate.
First of all, we want to be able to define the ViewModel behavior in its own “class” (in quotes because JavaScript doesn’t have true classes) so that there can be more than one instance of it: one to be bound to the UI and one to go into a test harness. That way, when the tests run, the UI wont’t act like it’s been possessed by a hyper-manic poltergeist because the tests are manipulating their own unbound instance. The typical way of creating a ViewModel does not allow for this.
var viewModel = kendo.observable({ message: 'Hello world!' }); // Can't create another instance of viewModel. Boo!
However, if you just make a slight change to the way you declare a ViewModel class, you can accomplish the goals stated above. All kendo.observable() does is wrap the object you pass it in an ObservableObject instance. So what if you define your own custom ObservableObject subclass?
var TestableViewModel = kendo.data.ObservableObject.extend({ message: 'Hello world!' }); // New instances can be created with new TestableViewModel() and they'll all have their own observable message property!
At its core, that’s really all you have to do in order to get started writing your own testable ViewModel classes. There are some challenges when it comes to testing DataSources, and that will be the subject of my next post. Meanwhile, please take a look at this JSBin to see a fully functional, if trivial, application that takes the above concept and fleshes it out to include a bound UI and a small suite of Jasmine unit tests operating on their own private instances of the same ViewModel.
The post Testable ViewModels with Kendo and Jasmine appeared first on Falafel Software Blog.