Test-driven developememnt (TDD) is a software development process. In this process, you write automated tests for expected functions; then, you write minimal code that satisfy these tests; finally, you refactor your code to meet your need (and still suffice your tests. Initially, developing in TDD way needs to write some extra code as tests; however, bugs can be reduced by fulfilling these tests during coding process. To simplifiy your testing tasks, using a testing framework is recommended. Here we introduce TDD in CoffeeScript with Jasmine.
Before we start our demo, install Jasmine, Grunt and CoffeeScript. (CoffeeScript itself is not strictly needed in our demo. But it’s fine to install it, since we want to do CoffeeScript programming.)
The content of package.json is like this:
To use Grunt, we need a Gruntfile as a automation script. Think it a list for possible automation tasks in this project. A nice feature of Grunt is its support for CoffeeScript; therefore, we can exploit this feature and write a Gruntfile.coffee file here:
Now, install local Node.js packages with
Then, initialize Jasmine tests:
If the project is properly set, we can start some tests:
Since there was no any test yet, there was no error occurred here. Before we start to write our hash code, let’s write some tests.
We want to test whether our hash is functional or not, so write down some tests in spec/lib/hash_spec.coffee.
There is no pre-defined way to write tests. Generally, you should write tests for both positive and negative conditions. Let’s write some real code. Add lib/hash.coffee in our project; write the constructor of our Hash class. We’ll use separated chaining in our hash.
Here we wrote a function object and immediately got its result. What we wanted was the array, not the function itself, so these parentheses were needed. Then, test our code again. You should see some failed tests here. Don’t worry. TDD way is meant to fulfill these failed tests.
Let’s implement our hash table. Edit lib/hash.coffee again:
We wrote an inner function here. Our tests wouldn’t touch this function. The spirit of TDD is separating interfaces from implementation. We used separating chaining to implement our hash table, but we didn’t do rehashing in this demo.
Test our code again:
Great. No further error occurred. But we had another question here: if our value was replaced by another one, the hash still worked? When in doubt, write tests.
Let’s do more tests. The result revealed that our code worked well.
With the combination of Jasmine and Grunt, you can write CoffeeScript code in TDD way. Let TDD be your friends; you’ll get better code.