About
:white_check_mark: A brief introduction to Test Driven Development (TDD) in JavaScript (Complete Beginner's Step-by-Step Tutorial)
## Why?
_Project(s) without tests_ often end up looking like they are stuck together with _**duct tape**_ ...
Change _one_ part and _another_ stops working? "_Fixing_" one bug, creates another?
Wouldn't you *prefer* it if everything was
***consistent*** and beautifully integrated?
What if _everyone_ on your team worked _like **clock-work**_ in a disciplined order... like a _**Formula 1 Crew**_ ...
Test Driven Development (TDD) makes your team a well-oiled machine which means you can go _**faster**_.
Once you have a ***suite*** of tests that run on every change, you will
begin to develop a whole other level of ***confidence*** in your codebase
and will discover a new freedom to be ***creative*** without fear of
"*breaking*" anything unexpectedly; truly *game-changing*.
## What?
This tutorial will help you get started with
**T**est **D**riven **D**evelopment (**TDD**) *today*!
In the next ***30 minutes*** you will learn _everything_1
you need to write tests for your web project!
### Pre-Requisites
+ **A computer** with a web browser
+ **Internet access** to download the starter files
+ **30 minutes** of your time
+ **_Basic_ Programming Skills** (HTML & JavaScript)
+ (_**Optional**_) _**Bonus Levels requires**_ you to
[_install_ **Node.js**](https://nodejs.org/download/)
### What is Software Testing?
> Software testing is the process of evaluating a software item to detect differences between the expected output and the actual output. Testing assesses the quality of the product. Software testing is a process that should be done during the development process. In other words software testing is a verification and validation process.
### What is TDD?
> Test-driven development (TDD) is an evolutionary approach to development
which combines test-first development, where you write a test before you write
just enough production code to fulfil that test, and refactoring. In other words,
it’s one way to think through your requirements
or design before you write your functional code.
*From [Introduction to Test Driven Development (TDD)](https://agiledata.org/essays/tdd.html)*
#### Further resources
- Software Testing - https://en.wikipedia.org/wiki/Software_testing
- "What is Software Testing" video (from 5:56 onwards) - https://youtu.be/UZy1Dj9JIg4?t=356
- Video intro to Software Development Lifecycle (from 0:52 onwards): https://youtu.be/qMkV_TDdDeA?t=52
- How to Write Clean, Testable Code - https://youtu.be/XcT4yYu_TTs (ignore the Java code focus on the general principles)
+ [What is software testing?](https://www.codeproject.com/Tips/351122/What-is-software-testing-What-are-the-different-ty) by _Rehman Zafar_
## How?
The *first* thing you need to *understand*
is that writing code following TDD (*discipline*)
is a (*slightly*) different approach from simply
diving into solving the problem (*without a test*).
When reading about TDD you will usually see the expression:
"***Red, Green, Refactor***":
What this means is that TDD follows a **3-step process**:
1. ***Write a Failing Test*** - Understand the (user)
requirements/story well enough to write a test for what you expect.
(_the test should **fail** initially - hence it being "Red"_)
2. ***Make the (failing) Test Pass*** - Write (*only*) the code you need
to make the (*failing*) test pass, while ensuring your existing/previous tests
all still pass (*no regressions*).
3. ***Refactor the code you wrote*** take the time to tidy up the code
*you* wrote to make it simpler
(*for your future self or colleagues to understand*)
before you need to ship the current feature, do it.
> Thankfully, because you will have good tests,
you don't _need_ to do any refactoring up-front,
you can always do refactoring _later_
if performance bottlenecks are discovered.
Most programming languages have very efficient compilers/interpreters
that remove much of the need for refactoring.
And if you use a linter your code will be naturally "tidy".
To develop the *habit(s)* you will need to be successful with TDD
(*and software engineering in general*)
we need to ***write*** a ***test first*** (*and watch it fail*)
and *then* write the code required to make the test pass.
Writing a _**failing test**_,
before writing the code may seem *counter-intuitive*,
*time consuming* or even "*tedious*" at _**first**_.
But we _urge_ you to think of it this way:
> The ***test*** is the ***question*** you are asking
> your code is the ***answer*** to the question.
> By having a _clear_ question, you can always check
> that your code is working,
> because it _**consistently**_
> gives you the same answer(s) ... _no surprises_,
even when you're working with a large, inter-dependent code base!
## Practical
> _**Note**: This tutorial is meant to be a beginner-friendly introduction to TDD.
The Vending Machine example is _intentionally_ simple
so you can focus on the principles of testing.
Once you understand the basics,
we encourage you to follow our _complete_ Todo List Tutorial
([https://github.com/dwyl/**todo-list-javascript-tutorial**](https://github.com/dwyl/todo-list-javascript-tutorial)),
which is a step-by-step guide to building an App
following testing and documentation-first best practices._
### Scenario: Vending Machine _Change Calculator_ Micro-Project
Imagine you are building a **Vending Machine**
that allows people to buy any item it contains.
The machine accepts coins and calculates the change
to be returned to the customer, given the item **price**
and the **cash** received.
### Single *File* App
We can build the _entire_ "project" in a _**single file**_: `index.html`
> _**Note**: In practice you want to split your JavaScript,
CSS and HTML (Templates) into **separate** files,
but for this example we are keeping everything in `index.html` for simplicity.
If you make it to the "Bonus Levels" you will split things out!_
Create a directory on your computer called **vending-machine**:
In your **terminal** type this command:
```sh
mkdir vending-machine && cd vending-machine
```
(_This will create the directory and move you into it_)
Next create a file called **index.html** e.g: `atom index.html`
(which creates and opens the file in the [Atom text editor](https://atom.io/)
if you have it installed)
(_**Note**: The "atom" command is not installed by default.
In the Atom menu bar there is a command named “Install Shell Commands”
which installs a new command in your Terminal called "atom"._)
Now copy-paste the following *sample code* into the newly created `index.html` file to get started:
```
…
```
#### Open index.html in your Browser
When you ***open*** `index.html` in your ***web browser***
you should expect to see something like this: (_without the annotation pointing out the qunit div, and the green and red annotations pointing out the Passing and Failing tests_)
##### Explanation
There is quite a lot of code in the **index.html** you just created,
let's step through it to understand the parts:
The first part of **index.html** is a standard HTML head and body:
```html
Vending Machine Change Calculator TDD
```
Nothing special here, we are simply setting up the page
and loading the CSS files.
Next we see the **qunit divs**
(_where the **test results** will be **displayed**_)
and load the JQuery and QUnit Libraries from CDN:
```html
```
Finally we see our test(s) - the interesting part of the file:
```html
```
If you are new to writing ***automated tests***, don't worry -
they are really simple. There are **3 parts**:
1. **Description** - usually the *first* parameter to QUnit's test() method, describing what is expected to happen in the test
2. **Computation** - executes a function/method
(*which invokes the method you will write to make your test pass*)
3. **Assertion** - verifies that the result of your computation
is what you ***expect*** it to be.
In the above screenshot, the assertion is `assert.equal(result, 2)`
We are giving the `equal` method two arguments; the `result` of our computation
and our expected value - in this case **2**. _That's it_.
_**Note**_:
The latest version of QUnit uses the `QUnit.test()` function to run tests.
Later in this workshop we use [blanket.js](https://blanketjs.org/)
which is not compatible with the latest
version of QUnit. It is for this reason
that we are calling `test()` to run the tests in this workshop.
##### Further Reading:
+ Test assertion: https://en.wikipedia.org/wiki/Test_assertion
+ What are Test Assertions and how do they work?:
https://www.thoughtworks.com/insights/blog/test-assertions-how-do-they-work
## Requirements
As a customer, I want to buy a selected item from the **vending machine**
and see what my change is as a **result** into the various **coins**
so that I can select one of the options and receive my change.
Acceptance criteria:
- A successful call of a function `getChange` should return
the change value in the various **coins** available
- Unit Tests should exist when the function is ready
- The selection of the desired return is out of scope
##### Complementary User Story view
> Given a **Price** and an amount of **Cash** from the Customer
> Return: **Change** to the customer (*in notes and coins*).
### Understand what is needed
+ Create a `function` called `getChange` that accepts _**two parameters**_:
`totalPayable` and `cashPaid`
+ For a given `totalPayable`
(the total amount an item in the vending machine costs)
and `cashPaid` (the amount of cash the customer paid into the vending machine),
`getChange` should _**calculate**_ the _**change**_
the machine should _return_ to the customer
+ `getChange` should _**return**_ change as an `array` of coins (largest to smallest)
that the vending machine will need to _dispense_ to the customer.
#### _Example_
If a customer buys an item costing £2.15
(_we represent this as **215 pennies**_ `totalPayable`)
and pays £3 (3 x £1 or _**300 pennies**_ `cashPaid`)
into the vending machine, the _**change**_ will be **85p**.
To dispense the 85p of change we should _return_
**four coins** to the person: 50p, 20p, 10p and 5p.
An **array** of these coins would look like: `[50, 20, 10, 5]`
#### Coins
In the UK we have the following Coins:
If we use the penny as the unit (i.e. 100 pennies in a pound)
the coins can be represented as:
- 200 (£2)
- 100 (£1)
- 50 (50p)
- 20 (20p)
- 10 (10p)
- 5 (5p)
- 2 (2p)
- 1 (1p)
this can be stored as an Array:
```javascript
var coins = [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.
#### The First Test
If you are *totally* new to TDD I recommend reading this
[introductory article](https://www.agiledata.org/essays/tdd.html) by Scott Ambler
(especially the diagrams) otherwise this (test-fail-code-pass) process
may seem *strange* ...
In **T**est **F**irst **D**evelopment (TFD) we write a test *first* and *then*
write the code that makes the test pass.
#### First Requirement
So, back in our **index.html*