Testing with CoffeeScript

Date posted
13 September 2012
Reading time
5 Minutes
Stephen Mahood

Testing with CoffeeScript

I was recently approached by Efendi Books to be the inaugural author of the new 'minibooks' series, titled 'Testing with CoffeeScript', which is available as a free download from the Efendi site.

 src=

CoffeeScript is something that has rather divided the JavaScript community. As a language that is compiled into JavaScript, it tries to make writing JavaScript easier, quicker and produce leaner code. For example, the following JavaScript:

var square = function(a) {
return a*a;
};

Is written much more succinctly with CoffeeScript:

square = (a) -> a*a

CoffeeScript takes a lot of inspiration from Ruby and Python, with indentation used to define scope over braces, no semi colons and an effort to abstract the bad parts, the common errors and the 'gotchas' that even experienced developers can fall for.

The book combines CoffeeScript and Behavioural Driven Development (BDD) in JavaScript through the testing library Jasmine. Unit testing gained a huge following in other languages, in particular Ruby (and Rails) and is slowly but surely gaining traction in the JavaScript community, with a whole host of testing libraries now available.

When starting with testing, it can be difficult to see the benefits, but once you've got a larger app (as built in the book), the benefits quickly become apparent. With a large set of tests covering all functionality, it means you're free to develop without fear of breaking anything you can verify that your new functionality works and your old functionality still works just by quickly running your tests.

There's also a huge advantage to writing your tests before implementation it gives you a great chance to think through the API of your application and how it will be used, before implementing. By having to write code that uses an API you've yet to write, it's very easy to fathom just how you'd like to structure your app, what methods and properties to expose and how the end developer will use it in reality.

Writing a book, even a relatively small one like this, is a great experience. They say that the best way to learn something is to teach it and I'd wholeheartedly back that up. There were more than a couple of occasions in which I ended up researching to clarify what I thought to be correct so I felt more comfortable writing about it and could explain it with a higher level of authority.

If you're interested in either CoffeeScript and/or Unit testing, I hope this book may be of use of you. So far it's received over 2,000 downloads and I've received some great feedback from people who have found it useful. If you do read it and would like to let me know what you thought, or have any questions, please feel free to get in touch.

About the author

Stephen Mahood