Sencha Touch BDD Part 2 -- Unit Testing Models
April 26, 2013
Let’s have some fun, shall we?
Test-Driven-Development starts with a test, of course. Let’s write one that just asserts that our model class exists:
When we run our tests in the browser, Jasmine reports this:
Error: [Ext.Loader] Failed loading synchronously via XHR: 'app/model/MyModel.js'; please verify that the file exists. XHR status code: 404
Which is just Ext’s very formal way of saying, “No such class exists” because we haven’t written it, yet.
Let’s write one that makes the test pass:
We have proven that we can create a new class, and that it’s name is what we expect.
Let’s assert that our model has some attributes:
Which of course, fails, until we add some fields to our model:
Let’s say that our model has some default values
Reload the Jasmine runner in the browser and …
SenchaBdd.model.MyModel has default values. Expected undefined to equal 'yellow'.
Which is easily resolved by adding it to the class:
One last simple piece, let’s assert that email is a required field.
The first expectation asserts that the model is not valid at all. It’s a gatekeeper test. The second test asserts that there’s validation error on the email field (and not some other field).
This is a pretty simple set of tests. If you are at all familiar with unit testing, you won’t find much new here. Testing for validations by inspecting on the Errors collection was a little tricky to suss out. Hopefully I’ve saved you a few frustrating moments digging through the source code. What’s also interesting, I think, is how the test report reads:
SenchaBdd.model.MyModel exists has data has default values requires an email address
The test itself communicates something to the reader about the intention of the model. That’s a key concept to understand about TDD; the most important and expensive reader of the application is not the browser, it’s the person who reads and maintains it. It might be your successor or your team mate, or perhaps, yourself, six months from now, when you’ve forgotten everything about this particular patch of code.