I have been experimenting more with
JavaScript frameworks lately. Being fond of the Test Driven
Development methodology, I came across Jasmine. Here is how the site
defines it: Jasmine
is a behavior-driven development framework for testing JavaScript
code. It does not depend on any other JavaScript frameworks. It does
not require a DOM. And it has a clean, obvious syntax so that you can
easily write tests.
If you have not already, download
Jasmine from http://pivotal.github.io/jasmine/
After you decompress the downloaded file you see this directory structure.
As you can see, the SpecRunner.html file is your user interface that is simply run from a web browser. The
spec folder will hold, as you guessed, your specification code—what
you want your implementation to do. The src folder will contain the
code you are testing.
The JavaScript includes in the SpecRunner.html file need to be set as such:
What I wanted to do was to test how
to sort a JavaScript array based on a date element in the array. So
let’s start with the spec file. I named my spec DateSortSpec.js and
placed it in the spec directory. Here is the DateSortSpec.js:
Next, the source code file,DateSort.js, goes in the scr directory:
OK, with basic structure in place let's do a sanity check and make sure we get a failing test result:
Now let’s get the “should show
Health for a Friend title with ascending sort” spec to pass. First,
create a function that will sort ascending by date. What I did was to
utilize the JavaScript array.sort method passing in a compare function.
Now reload the browser and the spec
passes.
Next we will add the spec to sort
descending.
Reload the browser and we see the
spec fail as we have not implemented any code for the spec.
So, the next step is clear.
Implement enough code to pass the spec. Here I again use the
JavaScript array.sort method passing in a function for a descending
comparator.
Refresh the browser again and bang!
As you can see using Jasmine is
pretty straight forward. Setup is a matter of expanding the
compressed file. Moreover, if one has a web browser and text editor
you a ready to code the specs and source code.