Why Don't You Use Tap?

21 Oct 2013 | By Alex Young | Tags node libraries testing

I always write tests for my Node projects, and I default to using Mocha. It’s popular with DailyJS readers and good at what it does. About two years ago Isaac Schlueter published tap, which is an implementation of the Test Anything Protocol. I wrote about it back in 2010, but haven’t used it very often.

The TAP will appeal to you if you’ve ever had to deal with “corporate” CI servers and overcomplicated XML protocols. The protocol is inherently simple, so it’s easy to both produce and consume it. That means you can write tools that do things with tests, and plug tools together.

Also there are browser-friendly modules out there. Tape by Substack is a tap-producing test harness that works in browsers thanks to Browserify.

One thing I like about Isaac’s tap module is the tests feel natively asynchronous. The TAP itself is based around streams of test data, so it’s no surprise that it fits in well with Node. However, it’s the API that I really like: every test case must be ended with .end(), or the number of assertions is declared with .plan(n).

Why is declaring the number of assertions (tests) useful? Well, in Node projects we tend to nest asynchronous calls, so it makes sense to ensure assertions were run at all. I’ve seen many tests over the years that had assertions that would never be reached, yet the tests still passed because there was no way to express this.

Another thing I like about the Isaac’s tap module is the tests can be run with node test_file.js, because the module has to be loaded like this:

var test = require('tap').test;

test('make sure the thingie is a thing', function(t) {
  t.equal(thingie, 'thing', 'thingie should be thing');
  t.type(thingie, 'string', 'type of thingie is string');
  t.end();
});

Because test is loaded from the tap module, we can run the test with the Node command-line binary, or use Isaac’s provided tap command which collates results with the tap-results module.

Also, assertions are included in the t instance, so everything is neatly organised.

I’ve noticed that some prominent Node developers like Substack continue to use the TAP, but I feel like it’s fallen out of favour in the Node community. So, I want to inspire a TAP renaissance. Give it a try, and see how it compares with your preferred test framework.


blog comments powered by Disqus