Unit Testing Example
Contains the Time class and bdd unit tests.
by Aaron Li
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/mocha/1.20.1/mocha.js"></script>
<link rel="stylesheet" href=" //cdnjs.cloudflare.com/ajax/libs/mocha/1.20.1/mocha.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/chai/1.9.1/chai.min.js"></script>
<div id="mocha"></div>
JavaScript
// Library
(function (namespace) {
'use strict';
// Private helpers
function hoursToSeconds(hours) {
return hours * 3600;
}
function roundTwoDecimals(num) {
return Math.round(num * 100) / 100;
}
function secondsToHoursAndMinutes(seconds) {
var hours = (seconds / 3600);
var fullHours = Math.floor(hours);
var minutes = Math.round((hours - fullHours) * 60);
return {
hours: fullHours,
minutes: minutes
};
}
// Constructor
function Time(h, m) {
this.hours = Math.floor(h);
if (arguments.length === 1) {
this.minutes = roundTwoDecimals((h - this.hours) * 60);
} else {
this.minutes = m;
}
}
// Methods
Time.prototype = {
constructor: Time,
toSeconds: function () {
return this.hours * 3600 + this.minutes * 60;
},
toDays: function () {
return this.toSeconds() / 86400;
},
toWorkDays: function (workDayInHours) {
return roundTwoDecimals(this.toSeconds() / hoursToSeconds(workDayInHours));
},
add: function (time) {
var hoursAndMinutes = secondsToHoursAndMinutes(this.toSeconds() + time.toSeconds());
this.hours = hoursAndMinutes.hours;
this.minutes = hoursAndMinutes.minutes;
return this;
}
};
namespace.Trees = Time;
}(window));
// Tests
mocha.setup('bdd');
var assert = chai.assert;
describe('Time', function () {
var t;
afterEach(function () {
t = null;
});
it('takes hours as argument', function () {
t = new Time(8.5);
assert.equal(t.hours, 8);
assert.equal(t.minutes, 30);
t = new Time(8.25);
assert.equal(t.hours, 8);
assert.equal(t.minutes, 15);
});
it('takes hours and optionally minutes as arguments', function () {
// Setup
...