learn-tape
v2.0.7
Published
Simple Test Driven Development (TDD) Tutorial using Tape
Downloads
32
Readme
Learn Tape ~ Testing in JavaScript
A Beginner's Guide to Test Driven Development (TDD) using Tape and Tap including front-end testing with JSDOM.
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". 📝✅
Why?
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.
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
orimport
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
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 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.
Background Reading
- 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
Who?
People who write tests for their Node.js or Frontend JavaScript code. (i.e. everyone that writes JavaScript!)
How?
Initialise
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:
npm init -y
That will create a basic package.json
file with the following:
{
"name": "learn-tape",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
That's enough to continue with the learning quest.
We will update the "scripts"
section later on.
If you are curious and want to understand the package.json
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
Install tape
using the following command:
npm init -y && npm install tape --save-dev
You should see some output confirming it installed:
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
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:
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.
Mini TDD Project: Change Calculator
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:
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
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
in the ./lib
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:
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
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:
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"):
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)
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. 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
:
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
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.
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 -D
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:
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 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:
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
Next you have to bundle your test files. Run the following browserify command:
node_modules/.bin/browserify test/*.js > lib/bundle.js
Create a
test.html
file that can hold your bundle:touch lib/test.html
Add your test script to your newly created
test.html
:echo '<script src="bundle.js"></script>' > lib/test.html
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:
Install
testling
:npm install testling -D
Run the following command to print your test results in your terminal:
node_modules/.bin/browserify test/*.js | node_modules/.bin/testling
You should see something that looks like this:
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 quite straightforward.
First 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
Next add a basic .travis.yml
file to your project:
language: node_js
node_js:
- "node"
And enable the project on Traivs-CI. Done.
Frequently Asked Questions
Can We Use Tape for Frontend Tests?
Now that you've learned how to use Tape to test your back end code check out our guide on frontend testing with tape.
What about Tap?
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
t.plan(2)
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:
1..3
ok 1 - Input file opened
not ok 2 - First line of the input valid
ok 3 - Read the rest of the file
# tests 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:
npm install tap-spec --save-dev
And then pipe the output of your test(s) through tap-spec:
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 version 13
# calculateChange(215, 300) should return [50, 20, 10, 5]
ok 1 should be equivalent
# calculateChange(486, 600) should equal [100, 10, 2, 2]
ok 2 should be equivalent
# calculateChange(12, 400) should return [200, 100, 50, 20, 10, 5, 2, 1]
ok 3 should be equivalent
# calculateChange(1487,10000) should equal [5000, 2000, 1000, 500, 10, 2, 1 ]
ok 4 should be equivalent
# should return -1 when the value is not present in Array
ok 5 should be equal
# sum should return the addition of two numbers
ok 6 should be equal
1..6
# tests 6
# pass 6
# ok
If you run the command:
npm run spec
You should see the "spec" formatted output:
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.