Simple Test Driven Development (TDD) Tutorial using Tape
npm install learn-tape






A Beginner's Guide to Test Driven Development (TDD) using Tape
and Tap including front-end testing with JSDOM.
alt="Volvo cars are safer because they learn from every real world crash!">
alt="Car Designers follow a Testing Mindset">
>
Note: this guide is _specific_ to testing
with Tape and Tap.
If you are new to Test Driven Development (TDD) in _general_,
consider reading our _beginner's introduction_:
github.com/dwyl/learn-tdd
The "vending machine" example/tutorial is _designed_ to be simple
for complete beginners.
If you prefer a more _extended_ "real world" example app, see:
github.com/dwyl/todo-list-javascript-tutorial
We _highly_ recommend learning the fundamentals here _first_
before diving into the bigger example.
Once you are comfortable
with the Tape/Tap syntax, there is a clear "next step". 📝✅
Testing your code is essential to ensuring reliability.
There are _many_ testing frameworks so it can be
difficult to choose.
Most testing frameworks/systems 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 Antoine's principal:

We use Tape because its minimalist feature-set
lets us craft simple maintainable tests that run fast.
+ 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.
> For more elaborate reasoning for using Tape, read:
https://medium.com/javascript-scene/why-i-use-tape-instead-of-Tape-so-should-you-6aa105d8eaf4
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 and 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.
+ Tape website: https://github.com/substack/tape
+ Test Anything Protocol (TAP) https://testanything.org/
+ Test Anything Protocol - gentler introduction:
https://en.wikipedia.org/wiki/Test_Anything_Protocol
People who write tests for their Node.js or Frontend JavaScript code.
(_i.e. everyone that writes JavaScript!_)
In your existing (_test-lacking_) project or a new learning directory,
ensure that you have a package.json file
by running the npm init command:
``sh`
npm init -ypackage.json
That will create a basic file with the following:`js`
{
"name": "learn-tape",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}"scripts"
That's enough to continue with the learning quest.
We will update the section later on. package.json
If you are _curious_ and want to _understand_ the file
in more detail, see: https://docs.npmjs.com/files/package.json
> If you are pushing your learning code to GitHub/GitLab,
consider adding a
.gitignore
file too.
Install tape using the following command:
`sh`
npm init -y && npm install tape --save-dev
You should see some output confirming it installed:
#### Create Test _Directory_
In your project create a new /test directory to hold your tests:
`sh`
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:
`js
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:
`sh`
node test/learn-tape.test.js
> Note: we use this naming convention /test/{test-name}.test.js/test
for test files in our projects so that we can keep other "_helper_" files
in the 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
Copy the following code into a new file called test/make-it-pass.test.js:
`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:
Try writing the code required in the sum function to make the test _pass_!
Great Succes! Let's try something with a bit more code.
We are going to build a basic cash register change calculator
following TDD using tape.
>
Note: this should be _familiar_ to you
if you followed the _general_
https://github.com/dwyl/learn-tdd
tutorial.
#### 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:
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:
`javascript`
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/test
in your directory and add the following lines:
`javascript`
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):
`sh`
node test/change-calculator.test.js
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 change-calculator.js./lib
in the directory.
> Note: We are not going to add any code to it _yet_.
This is _intentional_.
Re-run the test file in your terminal,
you should expect to see _no output_
(_it will "pass silently" because there are no 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:
`javascript
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();
});
`node test/change-calculator.test.js
Re-run the test file:
#### Export the calculateChange Function
Right now our change-calculator.js file does not _contain_ anything, require
so when it's '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:
`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:
`javascript`
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"_):
> 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:
`javascript
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_)
#### Keep Cheating or Solve the Problem?
We could keep cheating by writing a series of if statements:
`javascript`
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.
Let's do that instead.
> Note: this is the _readable_ version of the solution!
Feel free to suggest a
more _compact_ function.
Update the calculateChange function in change-calculator.js:
`javascript
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;
};
`
> _Note: we prefer the "functional programming" approach
when solving the calculateChange function._
_We have used an "imperative" style here simply because
it is more familiar to most people ...
If you are curious about the the functional solution,
and you should be,
see_: https://github.com/dwyl/learn-tdd#functional
#### Add More Tests!
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
`javascript`
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();
});
> _Note: adding more test examples is good way of achieving confidence
in your code. We often have 3x more example/test code than we do "library" code
in order to test all the "edge cases".
If you get the point where feel you are "working too hard" writing tests,
consider using_
"property based testing"
_to automate testing thousands of cases_.
- - -
#### 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.istanbul
If you are new to check out tutorial:
https://github.com/dwyl/learn-istanbul
Install istanbul from NPM:
`sh`
npm install istanbul -D
Run the following command (_in your terminal_) to get a coverage report:
`sh`
node_modules/.bin/istanbul cover node_modules/.bin/tape ./test/*.test.js
You should expect to see something like this:
or if you prefer the lcov-report:
> 100% Coverage for Statements, Branches, Functions and Lines.
If you need a shortcut to running this command, add the following to the scriptspackage.json
section in your ;
`sh`
istanbul cover tape ./test/*.test.js
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 -D
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 '' > 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 this:
#### 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 -D
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
> 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 quite straightforward.
First define the test script in your package.json:
`sh`
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_):
`sh`
istanbul cover tape ./test/*.test.js
Next add a basic .travis.yml file to your project:
`yml`
language: node_js
node_js:
- "node"
And _enable_ the project on Traivs-CI.
Done. 
Now that you've learned how to use Tape to test your back end code
check out our guide on
frontend testing with tape.
We use Tape for _most_ of our JavaScript testing needs
@dwyl
but _occasionally_ we find that having a few _specific_ extra functions
_simplifies_ our tests and reduces the repetitive "boilerplate".
If you find yourself needing a before or after function
to do "setup", "teardown" or resetting state in tests,
or you need to run tests in parallel
(_because you have lots of tests_),
then _consider_ using Tap:
tap-advanced-testing.md
vs. t.end()If you have multiple _asynchronous_ assertions in the same test,
you may want to use t.plan(2) at the start of your test.
For more detail, see: https://github.com/dwyl/learn-tape/issues/12
## Tap Spec?
One of the major advantages of Tap/Tape
is outputting the results of your tests
as text according to the
"Test Anything Protocol".
For example:
`sh`
1..3
ok 1 - Input file opened
not ok 2 - First line of the input valid
ok 3 - Read the rest of the filetests 3
pass 3
fail 0
This basic text output from our tests
can then be _re-formatted_ in a more _attractive_ format using a "reporter".
There are _several_ "reporters" available,
see: https://github.com/substack/tape#pretty-reporters
Our _favourite_ of these reporters is tap-spec:
https://github.com/scottcorgan/tap-spec
It's _super_ easy to use, simply install:
`sh`
npm install tap-spec --save-dev`
And then _pipe_ the output of your test(s) through tap-spec:sh`
tape ./test/*.test.js | tap-spec
That's it.
If you want to see the difference in output,
simply run the test in _this_ repository.
When you run the command:
``
npm run fast
You should see the "Normal" TAP output:
`tap
TAP version 13calculateChange(215, 300) should return [50, 20, 10, 5]
ok 1 should be equivalentcalculateChange(486, 600) should equal [100, 10, 2, 2]
ok 2 should be equivalentcalculateChange(12, 400) should return [200, 100, 50, 20, 10, 5, 2, 1]
ok 3 should be equivalentcalculateChange(1487,10000) should equal [5000, 2000, 1000, 500, 10, 2, 1 ]
ok 4 should be equivalentshould return -1 when the value is not present in Array
ok 5 should be equalsum should return the addition of two numbers
ok 6 should be equal
1..6
If you run the command:
`
npm run spec
`
You should see the "spec" formatted output:
`sh
calculateChange(215, 300) should return [50, 20, 10, 5] ✔ should be equivalent
calculateChange(486, 600) should equal [100, 10, 2, 2]
✔ should be equivalent
calculateChange(12, 400) should return [200, 100, 50, 20, 10, 5, 2, 1]
✔ should be equivalent
calculateChange(1487,10000) should equal [5000, 2000, 1000, 500, 10, 2, 1 ]
✔ should be equivalent
should return -1 when the value is not present in Array
✔ should be equal
sum should return the addition of two numbers
✔ should be equal
time=53.935ms
total: 17
passing: 17
duration: 101ms
``Not only do we get more information but it's more spaced out.
Play around with the different formatters/reporters and find one you like.
We're fans of _tap-spec_.