Read my book

I wrote books about Webpack and React. Check them out!

Thursday, March 29, 2012

suite.js - A Minimalistic Testing Tool for Node.js

As it so often happens while developing ghw (the GitHub wiki to GitHub pages converter thingy) I came by a nice and light syntax to use for testing. I took the syntax and then pushed it a bit further. As a result I have something I can now use on my Node projects.

In this post I'm going to introduce suite.js to you and show its basic capabilities. It's still in a very early stages but does some interesting things already. Besides basic testing functionality I've implemented generative tests (QuickCheck). The package, as ghw too, is available via npm.


Basic Idea


I borrowed the example below from ghw. It should give you some idea of how to use it. Those matchToHTML and matchToAST bits are just extra sugar I use to get the output I want. In normal cases it's enough to pass just a reference to the function you want to test here.


As you can see, the syntax is fairly light. suite.js is at its best when you need to test for equality like this. Note that the expected result may be a function too. In that case you may assert the way you want. The function receives the tested operation and parameters (usually just that one unless changed otherwise) and is expected to return boolean value based on whether or not the assertion passed. The generative tests handle their logic just this way as you'll see next.

Generative Tests


I derived the idea for generative tests from QuickCheck. It is a tool that was originally built for Haskell. The idea is quite simple. The concept depends on generators and invariants. It will perform actual tests based on these. I know that might sound a bit abstract so consider the following example:


As you can see it's quite trivial to generate a massive amount of tests using the scheme. The main benefit of this kind of testing is that it allows you to test and discover limits that you might not have thought to think of. Whereas unit tests focus on some certain aspect these kind of tests focus on certain invariant and make sure that's true.

Conclusion


suite.js is one of those small projects that sort of grew out of nothing. I've wanted to write a QuickCheck based tool for a while now. The concept seemed to fit the core of suite.js well so I bolted it in.

I'll continue to use suite.js on my Node projects and grow it as needed. Overall I like the light syntax and the way it's easy to extend. It doesn't get in my way and if it does, I can always stab it a bit.