Posterous theme by Cory Watilo

Simple testing for your algorithmic Javascript

Here's the backstory.

I noticed that Codebrawl does not yet support Github Flavored Markdown in Gist comments. Gist comments get loaded client-side via the Gist API and are then rendered with showdown.js. Showdown is a great project, but it does not support the extensions Github uses. This really sucks for gist comments which contain code, as they are rendered as regular Markdown-style code spans, which ignores newlines and indentation and makes them completely unreadable.

So I forked the project, added the necessary 30 lines of code and made a pull request. I "tested" my code the stupid way: Look at the output in the browser. This made me feel somewhat uneasy. I want this code to be useful, but how should anyone know that I did not break anything? I decided to add some tests. I have done testing in other languages, but never in Javascript. How do you do this?

Testing your Javascript

How can you test Javascript? JS usually runs in the browser, so you could just make an html page that runs your test code. The downside is that you need a browser and you need to refresh it. I'd rather work only on the command line for this project, as my JS does not really do anything that needs a DOM. It just translates one string to another. So what about testing it in node.js or something?

There is a really nice looking BDD testing framework for Javascript that also supports node.js: Jasmine by Pivotal Labs. It looks pretty much like what I want. It has an RSpec-like syntax and supports all kinds of run options. Having said that, I could not get it to run at all, at least not in under an hour. This was probably my own fault. Still, it drove me to think about what I actually needed and if I could just write it myself.

I really just want two things for this: RSpec-like syntax and RSpec-like output. I like the descriptive "it should do somethign", but I don't need all this beautiful "things.should be_wonderful" stuff, a simple assert_equal would be enough. 

Here is what I came up with.

This allows you to write tests like this:

Looks kinda okay! Now to run the tests, just run the specs through node.js. Here is a screenshot.

Jstestsuccess

Nice! How does it look if it fails?

Jstestfail

Also nice! I think I'll use this for now.

This is of course not a full featured solution. Right now, it only has an assert_equal method to test things - you could easily add more methods, though. I found that this mini-framework works quite well for my DOM-less algorithmic javascript, without introducing any external dependencies. If you have a similar problem, you might want to check out my showdown fork at https://github.com/rogerbraun/showdown and see how I use this.

Have fun!