//

TAPE & TAP

Tape & Tap are testing tools you can use instead of Mocha or Jasmine. The Test Anything Protocol (TAP) is a definition that has been around since 1987 and Tape is a test harness written in JavaScript for Node and the browser.

Why not Mocha, Jasmine etc?

Even though hugely popular, Mocha and Jasmine have their own gotchas.

Globals

Global functions like describe and it pollute the global environment.

Too much Configuration

Mocha needs an assertion library and also a reporting library, and then extra parameters to be passed on to Mocha for transpiling if the tests were written in ES6.

Shared State

Functions called before and after like beforeEach and afterEach would encourage sharing state between tests. But Tape would use setup and teardown functions for individual tests, the state will be retained in the local variables.

TAP

Tap formats test results in an easy to read format:

TAP version 13
# equivalence
ok 1 these two numbers are equal
 
1..1
# tests 1
# pass  1
 
# ok

TAP also allows us to pipe results generated from other tools following TAP protocol.

Example

Before we start, we need to install tape, so we can run tests in Node.

npm install tape -g

You don’t need to install tape globally, if you are not running tests in command line. Ideally you should have tape and tap-sepc installed as devDependencies.

npm install tape tap-spec ––save–dev

Now let’s look at a simple example on how to use Tape.

var test = require('tape');
 
test('Equation test', function (t) {
    t.equal(1, 1, '1 should be equal to 1');
    t.end();
});

We bring in the Tape module using require. Assuming you have Node environment setup, we can run the tests in command line.

tape tests/**/*.js

If you compared the same test with mocha you will realise that you will need to write more code with describe and it methods.

var assert = require("assert");
 
describe('Equation test', function(){
  it('1 should be equal to 1', function(){
    assert.equal(1, 1);
  })
})

Unlike Mocha, Tape doesn’t need a test runner. You can run tests as modules with Node.

Less abstraction means Tape code is easier to read and understand.

ES6 If you are like me and love write your JavaScript code in the latest and the greatest features ES6 has to offer, you can do so with the help of Babel via a require hook called babel-register.

Now we can use ES6 features to write tests.

var test = require('tape');
 
test('Equation test', (t) => {
    t.equal(1, 1, '1 should be equal to 1');
    t.end();
});

To run tests, now we need the babel-register flag.

tape -r babel-register tests/test02.js

The -r flags makes sure babel-register loads before running any tests, to allow for JIT compilation.

Conclusion

The code snippets for this post can be found on Github.