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:





Tuesday, September 25, 2012

Simple Web API

The few last months I have been playing around a lot with NodeJS. That has caused me to play with simple Rest API calls.  It's quite neat, you are basically able to do whatever you want with Javascript.  And using JSON you can quite easily communicate with your server.

I've recently installed Visual Studio 2012 ( thought I'd have a play with it), and I immediately wanted to play with the WebAPI.  It had already intrigued me when I had seen a talk by Glen Block about it at tech days.  Although, back then it was still unfinished.  So I was keen to see what it was doing now.  Since I had not played with MVC4, it's basically an intro for me.

When creating a new empty MVC4 project, the wizard will create a project structure.  Most notably for this spike it contains a "App_Start" and a "Controllers" folder.

The "App_Star" folder will contain a class called  WebApiConfig which has already some default routing setup to "/api/{controllerName}".

We can map a controller to this route by adding a new controller inheriting from the ApiController class in the "Controllers" folder.

public class NoteController : ApiController
    {
        public IEnumerable<Note> Get()
        {
            return new Note[] 
            { 
                new Note 
                {
                    Title = "ABC", 
                    Desciption = "value2" 
                } 
            };
        }
    }

The "Get" method basically maps to the Http GET method, it will do the same for POST, PUT, DELETE,...

What's cool is that it will serialize the DTO and output xml or json depending on the accept headers of the request.

If you want to force the output to be of another format you can  configure a querystring to output the correct result when calling the api.


GlobalConfiguration.Configuration
                .Formatters
                .JsonFormatter
                .MediaTypeMappings
                .Add(new QueryStringMapping("json", "true", "application/json"));

Calling "localhost/api/note?json=true" will then return : "[{"Title":"ABC","Desciption":"value2"}]"

To be fair, this does feel like a bulky way to do this, so if anyone knows of a better way, i'd be interested to know.