How to write you own testing library
lucassus opened this issue · comments
Lukasz Bandzarewicz commented
Lukasz Bandzarewicz commented
Initial work
function Suite(message, parent) {
this.message = message;
this.parent = parent;
this.tests = [];
}
Suite.prototype.fullMessage = function() {
var messages = [this.message];
if (this.parent) {
messages.unshift(this.parent.fullMessage());
}
return messages.join(' ');
};
function Test(message, parent, fn) {
this.message = message;
this.parent = parent;
this.fn = fn;
}
Test.prototype.fullMessage = function() {
var messages = [this.parent.fullMessage(), this.message];
return messages.join(' ');
};
var suites = [];
function describe(message, fn) {
var parent = suites[suites.length - 1];
var suite = new Suite(message, parent);
suites.push(suite);
fn.call(suite);
}
function it(message, fn) {
var parent = suites[suites.length - 1];
var scenario = new Test(message, parent, fn);
parent.tests.push(scenario);
}
function run() {
suites.forEach(function(suite) {
suite.tests.forEach(function(test) {
try {
test.fn.call(test);
console.log('OK: ', test.fullMessage());
} catch(error) {
console.log('ERROR:', test.fullMessage());
console.log(error.message);
console.log(error.stack);
}
});
});
}
function assert(condition, message) {
if (!condition) {
throw new Error(message);
}
}
describe('Suite', function() {
describe('.message', function() {
var suite = this;
it('returns a message', function() {
assert(suite.message === '.message');
});
});
describe('.fullMessage()', function() {
var suite = this;
it('returns the full message', function() {
assert(suite.fullMessage() === 'Suite .fullMessage()');
});
});
});
describe('Test', function() {
describe('.message', function() {
it('returns a test message', function() {
var test = this;
assert(test.message === 'returns a test message');
});
});
describe('.fullMessage()', function() {
it('returns the full test message', function() {
var test = this;
assert(test.fullMessage() === 'Test .fullMessage() returns a test message');
});
});
});
run();