PROGRAMMING

  minte9
learningjourney




S R Q

Browser

Automated tests are written separately, in addition to the code.
 
<!DOCTYPE html>
<html>
<head>
    <link href="https://cdn.jsdelivr.net/npm/mocha@9.1.4/mocha.css" 
        integrity="sha256-a4j/9d0TJl1bbNF1UC8zUh8pnur9RLQIyyaGAVtj8fM=" 
        crossorigin="anonymous" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/mocha@9.1.4/mocha.js" 
        integrity="sha256-wl8hYFZuIeOkXAmxbny9ku7nrD7qcAu7ybl5ZzyBG4g=" 
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/chai@4.3.4/chai.js" 
        integrity="sha256-80GiP7ACKKHzARzuCmIkx5TLAUSPlcl7cUd9d5wT4ZU=" 
        crossorigin="anonymous"></script>
</head>
<body>
    <script>

        function isEven(n) { // code to be tested
            return n%2 == 0;
        }

        function isOdd(n) {
            return n%2 != 0;
        }


        mocha.setup('bdd'); // minimal setup
        let assert = chai.assert; // assert library
        
        describe('isEven', function() {
            it('Check if number is even', function() {
                assert.equal(isEven(6), true);
                assert.equal(isEven(5), false);
            });
        });
        describe('isOdd', function() {
            it('Check if number is odd', function() {
                assert.equal(isOdd(8), false);
                assert.equal(isOdd(11), true);
            });
        });
    </script>

    <div id="mocha"></div>
    <script>
        mocha.run(); // from VsCode -> Open Live Server
    </script>

</body>
</html>

Node

Mocha allows you to use any assertion library you wish.
 
/**
 * bdd.test.js
 * 
 * BDD, Behavior Driven Development (tests, docs, examples)
 * 
 * Mocha, the core framework
 * Chai, the library with many assertions
 * javascript-pages/package.json
 * 
 * npm install --save-dev mocha
 * npm install --save-dev chai
 * cd javascript-pages/main/testing/mocha/
 * npm test
 * npm test -- --grep 'isOdd'
 * 
 */


function isEven(n) { // ode to be tested, usually in separate file
    return n%2 == 0;
}

function isOdd(n) {
    return n%2 != 0;
}

let assert = require('assert'); // node.js OR ...
assert = require('chai').assert; // chai

describe('isEven', function() {
    it('Check if number is even', function() {
        assert.equal(isEven(6), true);
        assert.equal(isEven(5), false);
    });
});

describe('isOdd', function() {
    it('Check if number is odd', function() { // it.only()
        assert.equal(isOdd(8), false);
        assert.equal(isOdd(11), true);
    });
});

Questions    
Last update: 63 days ago
Nested describe