> For the complete documentation index, see [llms.txt](https://heronyang.gitbook.io/clean-up-your-spaghetti/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://heronyang.gitbook.io/clean-up-your-spaghetti/3_ideal_coding_process_and_principles/test_driven_development.md).

# Test Driven Developement

## Cycle

* Add a test
* Run all tests and see if the new one fails
* Write some code
* Run tests
* Refactor code

Repeat

## Why

* Immediate feedback (bugs are found earlier)
* Make sure you don't break previous code
* Help refactor code (don't have to worry too much) ex. better policy

## Why Not

(from [Stackoverflow](http://stackoverflow.com/questions/64333/disadvantages-of-test-driven-development))

* Big time investment
* Additional Complexity
* Design isn't clear at first

## Practice

Create a folder and add following files:

* index.html

  ```markup
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>TDD Practice</title>
        <link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.20.0.css">
    </head>
    <body>
        <div id="qunit"></div>
        <div id="qunit-fixture"></div>
        <script src="http://code.jquery.com/qunit/qunit-1.20.0.js"></script>
        <script src="main.js"></script>
        <script src="tests.js"></script>
    </body>
    </html>
  ```
* tests.js

  ```javascript
    QUnit.test("hello test", function( assert ) {
        assert.ok( 1 == "1", "Passed!" );
    });

    QUnit.test('max', function (assert) {

    });

    QUnit.test('isOdd', function (assert) {

    });
  ```

Then, let's start to edit `main.js`! Our goal is to **write unit tests first** and **implement main.js to pass all the tests**.

## Reference

* [Getting Started with QUnit](http://www.sitepoint.com/getting-started-qunit/)
