PROGRAMMING

 
REMEMBERS




Last update:   29-10-2021

Why

When we write a function, we can usually imagine what it should do: which parameters give which results. If something is wrong – then we fix the code, run again, check the result – and so on till it works. But such manual “re-runs” are imperfect. For instance, we’re creating a function f. 1) Wrote some code, testing: f(1) works, but f(2) doesn’t work. 2) We fix the code and now f(2) works. Looks complete? 3) But we forgot to re-test f(1). Automated testing means that tests are written separately, in addition to the code.

BDD

Let’s start with a technique named Behavior Driven Development. BDD specifies that business analysts and developers should collaborate in this area and should specify behavior in terms of user stories, which are each explicitly written down in a dedicated document. In BDD, the spec goes first, followed by implementation.

Describe it

Let’s say we want to make a function pow(x, n). Before creating the code of pow, we can imagine what the function should do and describe it. Such description is called a specification and contains descriptions of use cases together with tests for them.
 
// test.js

describe("pow", function() {
  it("raises to n-th power", function() {
    assert.equal(pow(2, 3), 8);
  });

});
... 1 lines
 
The specification can be executed, and it will run the test specified in it block.

Example

 
<html>
<head>

<!-- add mocha, framework code -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/3.2.0/mocha.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/3.2.0/mocha.js"></script>
<script>
    mocha.setup('bdd'); // minimal setup
</script>
</head>
<body>

<script>
    function pow(x, n) {
      /* function code is to be written, empty now */
      //return 8;
    }
</script>

<!-- the script with tests (describe, it...) -->
<script>
    describe("pow", function() {

        it("raise to n-th power", function() {
            assert.equal(pow(2,3), 8);
        });
    });
</script>

<!-- this element will contain test results -->
<div id="mocha"></div>

<!-- run tests! -->
<script>
    mocha.run();
</script>
</body>
</html>
... 27 lines
 

Questions    
Object-basics