Saturday, November 3, 2012

Writing Javascript tests for Mocha in CoffeeScript

These days I am working a lot with JavaScript, for testing, we chose to write readable tests in CoffeeScript, and executing these in Mocha.

Testing your code in JavaScript, to me, is even more important then in a compiled language (for example: C#), because you miss the convenience of a compiler that will already check your syntax. 

Using CoffeeScript in combination with Mocha-Cakes, I find, makes your tests very readable.
Mocha Cakes provides the Given/When/Then syntax, allowing you to clearly explain the behavior.

Lets say we want to test the following piece of code, written in JavaScript : 
var Foo = function(config){
    this.config = config;
}

Foo.prototype = {
    getAnswer: function(){
        return this.config ? "Bar" : "Bazz";
    }
}
module.exports = Foo;

We might want to write a test, to test the behavior based on the configuration that is given to Foo.  That test might look something like this, written in CoffeeScript.
Foo = require "../js/foo"

Feature "Foo, In order to get an answer as a user I want to get a result", ->;
    Scenario "With a configuration", ->;
        Given "Foo is created with a configuration", ->;
            @foo = new Foo("showBar")

        When "An answer is requested", ->;
            @response = @foo.getAnswer()
 
        Then "Answer given is 'Bar'", ->;
            @response.should.equal("Bar")

    Scenario "Without a configuration", ->;
        Given "Foo is created without a configuration", ->;
            @foo = new Foo();

        When "An answer is requested", ->;
            @response = @foo.getAnswer()

        Then "Answer given is 'Bazz'", ->;
            @response.should.equal("Bazz")
This syntax is very readable and allows you to quickly understand what is going on, and what behavior is expected.

To get mocha to run your CoffeeScript tests, you will need a "mocha.opts" file, containing the options that mocha will use.

--require should
--require mocha-cakes
--reporter spec
--compilers coffee:coffee-script
--recursive

When everything is up and running, when starting mocha in the command line, your test result should look something like this:





No comments:

Post a Comment