Setting up tests using Tape

Test driven development has become an important process in the software engineering world. It allows coders to develop functions by first creating a series of tests that the new function must solve. The benefit of this is that once your app grows more complex and you add new functionality, you can see if any existing tests have failed, meaning that something broke (and now you know where to find it). Look no further than any popular project on Github and you’ll often see a “tests” folder.

Today, we’re going to talk about setting up tests using Tape.

Tape is an alternative to popular testing suites such as Jasmine and Mocha. Like any tool related to software engineering, there are some developers that strongly prefer Tape over other options. It’s fairly easy to setup and can easily be run in automated task runner tools such as Grunt and Gulp.

To use it as part of your project, you can install it through npm:

  npm install tape --save-dev

Once it’s been added as part of your project, you can create a new tests.js file and require the module.

For our demonstration, we’re going to write a simple test that checks if my name is Dave, plus a few additional parameters.

Start off by setting up your test.js file like so (you can name it whatever you prefer). I’ve commented the code for some additional clarity on what’s happening here.

// Require the Tape module imported from npm
var test = require('tape');

// Write your tests in the code block
test('All about Dave', function (t) {
    // The number of tests that you plan to run.
    // NOTE: If this number doesn't match up with the number
    // of tests that are run, your test will fail.
    t.plan(2);
    
    // Let's setup some variables to test
    var name = "Seymore";
    var city = "Oakland";
    var favBaseballTeam = "Athletics";

    // This test will check for my favorite baseball team.
    // The first parameter is the result, the second is
    // the value you're expecting, and the third is the message
    t.equal(favBaseballTeam, "Athletics", "Favorite baseball team should be Athletics");

    // This test will check for my name.
    // As you can probably assume, it will fail.
    t.equal(name, "Dave", "Name should be Dave");

    // This test will check if city has been set:
    if (city) {
      t.pass("City set");
    } else {
      t.fail("City not set");
    }
});

That’s it! You can run Tape from your terminal and point it to your newly created test.js file in order to run it.

Screenshot 2015-09-01 14.00.18