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
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:
We use Tape because it's minimalist feature-set lets you 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
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.
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/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 want to write tests for their Node.js or Web Browser JavaScript code. (i.e. ALL JavaScript coders!)
dwyl/learn-tape#7 (help wanted!)
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:
In your project create a new /test directory to hold your tests:
mkdir test
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();
});
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
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.
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 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
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
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)
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
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:
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 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)
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();
});
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:
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
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 --save-dev
- 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:
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 --save-dev
- 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:
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
Now that you're a pro at using Tape to test your back end code check out our front end testing with tape guide!