Skip to content

✅ Learn how to use Tape for JavaScript/Node.js Test Driven Development (TDD) - Ten-Minute Testing Tutorial

Notifications You must be signed in to change notification settings

diaaldin/learn-tape

 
 

Repository files navigation

Learn Tape

Build Status codecov Code Climate devDependencies Status contributions welcome

A Beginner's Guide to Test Driven Development (TDD) with Tape.

Note: if you are new to Test Driven Development (TDD), we have a more general beginner's introduction and background about testing: https://github.com/dwyl/learn-tdd

Why?

Testing your code is essential to ensuring reliability.

There are many testing frameworks so it can be difficult to choose, most try to do too much, have too many features ("bells and whistles" ...) or inject global variables into your run-time or have complicated syntax.

The shortcut to choosing our tools is to apply the golden rule:

perfection-achieved

We use Tape because it's minimalist feature-set lets you craft simple maintainable tests that run fast.

Reasons Why Tape (not XYZ Test Runner/Framework...)

  • No configuration required. (works out of the box, but can be configured if needed)
  • No "Magic" / Global Variables injected into your run-time (e.g: describe, it, before, after, etc.)
  • No Shared State between tests. (tape does not encourage you to write messy / "leaky" tests!)
  • Bare-minimum only require or import into your test file.
  • Tests are Just JavaScript so you can run tests as a node script e.g: node test/my-test.js
  • No globally installed "CLI" required to run your tests.
  • Appearance of test output (what you see in your terminal/browser) is fully customisable.

Read: https://medium.com/javascript-scene/why-i-use-tape-instead-of-Tape-so-should-you-6aa105d8eaf4

What?

Tape is a JavaScript testing framework that works in both Node.js and Browsers. It lets you write simple tests that are easy to read/maintain. The output of Tape tests is a "TAP Stream" which can be read by other programs/packages e.g. to display statistics of your tests.

Background Reading

Who?

People who want to write tests for their Node.js or Web Browser JavaScript code. (i.e. ALL JavaScript coders!)

How?

Tape Features (Subset)

dwyl#7 (help wanted!)

Install

npm install tape --save-dev

(For us newbies, I'd like to suggest you include the npm init step. We did this project in Iron Yard bootcamp, but didn't know to init npm, nor to add Node to the .gitignore file)

You should see some output confirming it installed:

learn-tape-install-save-dev

First Tape Test

Create Test Directory

In your project create a new /test directory to hold your tests:

mkdir test

Create Test File

Now create a new file /test/learn-tape.test.js in your text editor.

and write (or copy-paste) the following code:

const test = require('tape'); // assign the tape library to the variable "test"

test('should return -1 when the value is not present in Array', function (t) {
  t.equal(-1, [1,2,3].indexOf(4)); // 4 is not present in this array so passes
  t.end();
});

Run The Test

You run a Tape test by executing the file in your terminal e.g:

node test/learn-tape.test.js

your-first-tape-test-passing

Note: we use this naming convention /test/{test-name}.test.js for test files in our projects so that we can keep other "helper" files in the /test directory and still be able to run all the test files in the /test directory using a pattern: node_modules./.bin/tape ./test/*.test.js

Make it Pass

Copy the following code into a new file called test/make-it-pass.test.js:

const test = require('tape'); // assign the tape library to the variable "test"

function sum (a, b) {
  // your code to make the test pass goes here ...
}

test('sum should return the addition of two numbers', function (t) {
  t.equal(3, sum(1, 2)); // make this test pass by completing the add function!
  t.end();
});

Run the file (script) in your terminal: node test/make-it-pass.test.js

You should see something like this:

learn-tape-not-passing

Try writing the code required in the sum function to make the test pass!

learn-tape-make-it-pass

Great Succes! Let's try something with a bit more code.

Mini TDD Project: Change Calculator

Basic Requirements

Given a Total Payable and Cash From Customer Return: Change To Customer (notes and coins).

Essentially we are building a simple calculator that only does subtraction (Total - Cash = Change), but also splits the result into the various notes & coins.

In the UK we have the following Notes & Coins:

GBP Notes GBP Coins

see: http://en.wikipedia.org/wiki/Banknotes_of_the_pound_sterling (technically there are also £100 and even £100,000,000 notes, but these aren't common so we can leave them out. ;-)

If we use the penny as the unit (i.e. 100 pennies in a pound) the notes and coins can be represented as:

  • 5000 (£50)
  • 2000 (£20)
  • 1000 (£10)
  • 500 (£5)
  • 200 (£2)
  • 100 (£1)
  • 50 (50p)
  • 20 (20p)
  • 10 (10p)
  • 5 (5p)
  • 2 (2p)
  • 1 (1p)

this can be represented as an Array:

const coins = [5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1]

Note: the same can be done for any other cash system ($ ¥ €) simply use the cent, sen or rin as the unit and scale up notes.

Create Test File

Create a file called change-calculator.test.js in your /test directory and add the following lines:

const test = require('tape'); // assign the tape library to the variable "test"
const calculateChange = require('../lib/change-calculator.js');  // require (not-yet-written) module

Watch it Fail

Back in your terminal window, the test by executing the command (and watch it fail):

node test/change-calculator.test.js

Tape TFD Fail

This error (``Cannot find module '../lib/change-calculator.js'`) is pretty self explanatory. We haven't created the file yet so the test is requiring a non-existent file!

Q: Why deliberately write a test we know is going to fail...?
A: To get used to the idea of only writing the code required to pass the current (failing) test, and never write code you think you might need. see: YAGNI

Create the Module File

In Test First Development (TFD) we write a test first and then write the code that makes the test pass.

Create a new file for our change calculator /lib/change-calculator.js:

Note: We are not going to add any code to it yet.

Re-run the test file in your terminal, you should expect to see no output (it will "pass" because there are no tests)

Tape Pass 0 Tests

Add a Test

Going back to the requirements, we need our calculateChange method to accept two arguments/parameters (totalPayable and cashPaid) and return an array containing the coins equal to the difference:

e.g:

totalPayable = 210         // £2.10
cashPaid     = 300         // £3.00
difference    =  90         // 90p
change       = [50,20,20]  // 50p, 20p, 20p

Lets add a test to test/change-calculator.test.js and watch it fail:

const test = require('tape'); // assign the tape library to the variable "test"
const calculateChange = require('../lib/change-calculator.js');  // require the calculator module

test('calculateChange(215, 300) should return [50, 20, 10, 5]', function(t) {
  const result = calculateChange(215, 300); // expect an array containing [50,20,10,5]
  const expected = [50, 20, 10, 5];
  t.deepEqual(result, expected);
  t.end();
});

Re-run the test file: node test/change-calculator.test.js

Tape 1 Test Failing

Export the calculateChange Function

Right now our change-calculator.js file does not contain anything, so when it's require'd in the test we get a error: TypeError: calculateChange is not a function

We can "fix" this by exporting a function. add a single line to change-calculator.js:

module.exports = function calculateChange() {};

Now when we run the test, we see more useful error message:

learn-tape-first-test-failing

Write Just Enough Code to Make the Test Pass

We can "fake" passing the test by by simply returning an Array in change-calculator.js:

module.exports = function calculateChange(totalPayable, cashPaid) {
  return [50, 20, 10, 5]; // return the expected Array to pass the test
};

Re-run the test file node test/change-calculator.test.js (now it "passes"):

Tape 1 Test Passes

Note: we aren't really passing the test, we are faking it for illustration.

Add More Test Cases

Add a couple more tests to test/change-calculator.test.js:

test('calculateChange(486, 600) should equal [100, 10, 2, 2]', function(t) {
  const result = calculateChange(486, 600);
  const expected = [100, 10, 2, 2];
  t.deepEqual(result, expected);
  t.end();
});

test('calculateChange(12, 400) should return [200, 100, 50, 20, 10, 5, 2, 1]', function(t) {
  const result = calculateChange(12, 400);
  const expected = [200, 100, 50, 20, 10, 5, 2, 1];
  t.deepEqual(result, expected);
  t.end();
});

Re-run the test file: node test/change-calculator.test.js (expect to see both tests failing)

learn-tape-two-failing-tests

Keep Cheating or Solve the Problem?

We could keep cheating by writing a series of if statements:

module.exports = function calculateChange(totalPayable, cashPaid) {
    if(totalPayable == 486 && cashPaid == 1000)
        return [500, 10, 2, 2];
    else if(totalPayable == 210 && cashPaid == 300)
        return [50, 20, 20];
};

But its arguably more work than simply solving the problem. Lets do that instead. (Note: this is the readable version of the solution! feel free to suggest a more compact algorithm)

Update the calculateChange function in change-calculator.js:

module.exports = function calculateChange(totalPayable, cashPaid) {

  const coins = [5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1];
  let change = [];
  const length = coins.length;
  let remaining = cashPaid - totalPayable;          // we reduce this below

  for (let i = 0; i < length; i++) { // loop through array of notes & coins:
    let coin = coins[i];

    if(remaining/coin >= 1) { // check coin fits into the remaining amount
      let times = Math.floor(remaining/coin);        // no partial coins

      for(let j = 0; j < times; j++) {     // add coin to change x times
        change.push(coin);
        remaining = remaining - coin;  // subtract coin from remaining
      }
    }
  }
  return change;
};

Add one more test to ensure we are fully exercising our method:

totalPayable = 1487                                 // £14.87  (fourteen pounds and eighty-seven pence)
cashPaid     = 10000                                // £100.00 (one hundred pounds)
difference    = 8513                                 // £85.13
change       = [5000, 2000, 1000, 500, 10, 2, 1 ]   // £50, £20, £10, £5, 10p, 2p, 1p
test('calculateChange(1487,10000) should equal [5000, 2000, 1000, 500, 10, 2, 1 ]', function(t) {
  const result = calculateChange(1487,10000);
  const expected = [5000, 2000, 1000, 500, 10, 2, 1 ];
  t.deepEqual(result, expected);
  t.end();
});

Tape 4 Passing


Bonus Level

Code Coverage

Code coverage lets you know exactly which lines of code you have written are "covered" by your tests (i.e. helps you check if there is "dead", "un-used" or just "un-tested" code) We use istanbul for code coverage. If you are new to istanbul check out tutorial: https://github.com/dwyl/learn-istanbul

Install istanbul from NPM:

npm install istanbul --save-dev

Run the following command (in your terminal) to get a coverage report:

node_modules/.bin/istanbul cover node_modules/.bin/tape ./test/*.test.js

You should expect to see something like this:

learn-tape-coverage

or if you prefer the lcov-report:

Istanbul Coverage Report

100% Coverage for Statements, Branches, Functions and Lines.

If you need a shortcut to running this command, add the following to the scripts section in your package.json;

istanbul cover tape ./test/*.test.js

Run your Tape tests in the browser

Follow these steps to run Tape tests in the browser:

  1. You'll have to bundle up your test files so that the browser can read them. We have chosen to use browserify to do this. (other module bundlers are available). You'll need to install it globally to access the commands that come with it. Enter the following command into the command line: npm install browserify --save-dev
  2. Next you have to bundle your test files. Run the following browserify command: node_modules/.bin/browserify test/*.js > lib/bundle.js
  3. Create a test.html file that can hold your bundle: touch lib/test.html
  4. Add your test script to your newly created test.html: echo '<script src="bundle.js"></script>' > lib/test.html
  5. Copy the full path of your test.html file and then paste it into your browser. Open up the developer console and you should see something that looks like: browser

Headless Browser

You can print our your test results to the command line instead of the browser by using a headless browser:

  1. Install testling: npm install testling --save-dev
  2. Run the following command to print your test results in your terminal: node_modules/.bin/browserify test/*.js | node_modules/.bin/testling
  3. You should see something that looks like this: testling

Continuous Integration?

If you are new to Travis CI check out our tutorial: https://github.com/dwyl/learn-travis

Setting up Travis-CI (or any other CI service) for your Tape tests is easy simply define the test script in your package.json:

tape ./test/*.test.js

We usually let Travis send Code Coverage data to Codecov.io so we run our tape tests using Istanbul (see the coverage section above):

istanbul cover tape ./test/*.test.js

What about front end code with Tape?

Now that you're a pro at using Tape to test your back end code check out our front end testing with tape guide!

About

✅ Learn how to use Tape for JavaScript/Node.js Test Driven Development (TDD) - Ten-Minute Testing Tutorial

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 90.7%
  • HTML 5.5%
  • CSS 3.8%