Skip to content

Instantly share code, notes, and snippets.

@jnewman12
Last active March 2, 2017 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnewman12/7f0f50521a4a4db917981fb583f19a64 to your computer and use it in GitHub Desktop.
Save jnewman12/7f0f50521a4a4db917981fb583f19a64 to your computer and use it in GitHub Desktop.
Test Driven Development

Intro to Test Driven Development

TDD


Objectives

  • Understand the use case for testing your apps
  • Understand how to write tests

What is TDD?

Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: requirements are turned into very specific test cases, then the software is improved to pass the new tests, only.

Software testing is the process of evaluation a software item to detect differences between given input and expected 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 fulfill that test and refactoring. In other words, it’s one way to think through your requirements or design before you write your functional code.


Red, Green, Re-Factor

red, green, refactor

  • The Process of TDD is different than just diving into the code right away, and requires a certain level of patience

  • A common term you will hear related to this is Red, Green, Refactor. This is a 3 step process that includes;

    • 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")
    • 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).
    • Refactor the code you wrote - if you have 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.
  • 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.


How does code test code?

  • With TDD, under the hood, often consists of 3 parts

    • the code your testing, your condition
    • the success case or error case message
    • the code your testing against
  • Whether you are writing tests in rails, angular, python, or any other language, you will likely come across those 3 things

  • Under the hood it might look something like the following

function assert(message, condition) {
    if (!condition) {
      return message || "Assertion failed";
    } else {
      return 'test passed :)';
    }
}

function grabOne(arr, index) {
  return arr[index];
}

grabOne([1, 2, 3], 2) // => 3

console.log(assert('grabOne([1, 2, 3], 1) should equal 1', grabOne([1, 2, 3], 1) === 3));

Lets break this down

  • first we have our assert function that displays either a success or error message based on the condition
  • then we have the code it is testing
  • we then display a message based on the truthy or falsy value

An Example

  • Using Javascript to test our code, we are going to sample one of the popular javascript libraries called Q-Unit
  • Although it is not as complex as a testing service like Jasmine, it requires virtually no set up
  • Let's make a new directory in our computer, CD into it, and touch an index.html file
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Example Tests</title>
    <!-- Load the QUnit CSS file from CDN - Require to display our tests attractively -->
    <link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-1.18.0.css">
    <!-- Pure CSS is a minimalist CSS file we have included to make things look nicer -->
    <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css">
  </head>
  <body style='margin: 0 1em;'>
    <div id='main'>
      <h1>Some Awesome Sample Q-Unit Tests</h1>
    </div>

    <div id="qunit"></div>
    <div id="qunit-fixture"></div>
    <!-- Load the QUnit Testing Framework from CDN - this is the important bit ... -->
    <script src="https://code.jquery.com/qunit/qunit-1.18.0.js"></script>
    <script>
      // This is what a simple unit test looks like:
      test('This sample test should always pass!', function(assert) {
        var result = 1 + 1;
        assert.equal(result, 2); // just so we know everything loaded ok
      });

      // A failing test will be RED:
      test('This is what a failing test looks like!', function(assert) {
        var result = [1,2,3].indexOf(1);  // this should be 0
        assert.equal(result, -1); // we *expect* this to fail
      });

      // Another "RED" test
      test('This is string testing!', function(assert) {
        var result = 'Hi!'[0];
        assert.equal(result, '!');
      })
    </script>
  </body>
</html>

Your Turn

  • Now that we have gotten a little taste of it, lets pair up (or individually) and get all 3 of these tests pass
  • In your current folder, either make a new file, or get rid of everything in the old file and add this
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Example Tests</title>
    <!-- Load the QUnit CSS file from CDN - Require to display our tests attractively -->
    <link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-1.18.0.css">
    <!-- Pure CSS is a minimalist CSS file we have included to make things look nicer -->
    <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css">
  </head>
  <body style='margin: 0 1em;'>
    <div id='main'>
      <h1>Sample Test Cases</h1>
    </div>

    <div id="qunit"></div>
    <div id="qunit-fixture"></div>
    <!-- Load the QUnit Testing Framework from CDN - this is the important bit ... -->
    <script src="https://code.jquery.com/qunit/qunit-1.18.0.js"></script>
    <script>
      test('Average The Elements of an Array', function(assert) {
        var averageArray = function(array) {
          // your code here
        }
        var output = averageArray([13, 4, 5, 10]);
        assert.equal(output, 8);
      })

      test('Remove All Even Values From an Array', function(assert) {
        var onlyOddVals = function(array) {
          // your code here
        }
        var output = onlyOddVals([1, 2, 3, 4, 5, 6, 7, 8]);
        assert.deepEqual(output, [1, 3, 5, 7]);
      })

      test('Combine Two Arrays Together', function(assert) {
        var joinArrays = function(arr1, arr2) {
          // your code here
        }
        var output = joinArrays([1, 2], [3, 4]);
        assert.deepEqual(output, [1, 2, 3, 4])
      })
    </script>
  </body>
</html>

Resources


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment