Simple unit testing

by dtracers

HTML

<script src="http://code.jquery.com/qunit/qunit-1.17.1.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.17.1.css">
<script src="https://gist.githubusercontent.com/dtracers/8d2f709556633dfe0124/raw/4916b94cea9546abfa76f9825fb0083f011646cf/gistfile1.js"></script>
<div id="qunit"></div>
<div id="qunit-fixture"></div>

JavaScript

// testing our complex database code
function DataBase() {

    this.getValue = function(key) {
        if (typeof key === "undefined") {
            throw new Error("Key must be defined");
        }
        if (typeof this[key] === "undefined") {
            throw new Error("Must use valid key");
        }
        return this[key];
    }

    this.setValue = function(key, value) {
        this[key] = value
    }
}


QUnit.test("this test fails", function(assert) {
    var database = new DataBase();
    var result = database.getValue("Invalid Key");
    assert.equal(undefined, result);
});

QUnit.test("we catch the exception #1", function(assert) {
    var database = new DataBase();
    assert.throws (function() {
        database.getValue(undefined);
    });
});

QUnit.test("we catch the exception #2", function(assert) {
    var database = new DataBase();
    assert.throws (function() {
        database.getValue("Invalid Key");
    });
});