Skip to content

Instantly share code, notes, and snippets.

@ryan-blunden
Created December 19, 2011 06:23
Show Gist options
  • Save ryan-blunden/1495692 to your computer and use it in GitHub Desktop.
Save ryan-blunden/1495692 to your computer and use it in GitHub Desktop.
Basic BDD example for addClass method
/**
* Experimenting with no frills BDD to write a simple addClass method
*/
function TestSuite(name, setup, teardown) {
var leftPadding = 60;
this.name = name || '';
this.tests = [];
this.setup = setup || function() {},
this.teardown = teardown || function() {};
this.addTest = function(description, tests) {
this.tests.push(function() {
console.log(description + ' =>' + (function(num) { var pad = ''; while(num--) { pad += ' '; } return pad; })(leftPadding-description.length), tests() ? 'pass' : 'fail');
});
return this;
};
this.run = function() {
this.name && console.log(this.name + ' Test Suite')
for(var i=0; i<this.tests.length; i++) {
this.setup();
this.tests[i]();
this.teardown();
}
return this;
}
};
function addClass(elem, newClassName) {
var className, classes, classesLength;
if(typeof elem === 'string') {
elem = document.getElementById(elem);
}
if(elem === null || elem.nodeType !== 1 || typeof newClassName !== 'string') {
return null;
}
className = elem.className;
classes = newClassName.split(' '),
classIndex = classes.length;
while(classIndex--) {
className = (className.match(new RegExp('\\b'+classes[classIndex]+'\\b')) === null ? className +' '+ classes[classIndex] : className);
}
elem.className = className;
return elem;
}
(function() {
var element = {
className: 'top left float'
},
setup = function() {
document.body.appendChild(
(function() {
var e = document.createElement('div');
e.setAttribute('id', 'addClassTest');
e.className = element.className;
e.innerHTHML = 'Ryan\'s Test Div';
return e;
})()
);
},
teardown = function() {
document.body.removeChild(document.getElementById('addClassTest'));
};
new TestSuite('addClass', setup, teardown)
.addTest('Resolves element by id if string passed in for elem', function() {
return addClass('addClassTest', 'test') !== null;
})
.addTest('Returns null if non-existent id string passed in for elem', function() {
return addClass('WTF', 'test') === null;
})
.addTest('Does not add duplicate classes (single class)', function() {
return addClass('addClassTest', 'top').className == element.className;
})
.addTest('Does not add duplicate classes (mulitple classes)', function() {
return addClass('addClassTest', 'top float').className == element.className;
})
.addTest('Adds new classes', function() {
return addClass('addClassTest', 'newClass').className == element.className + ' newClass';
})
.addTest('Adds new classes (multiple classes)', function() {
return addClass('addClassTest', 'newClass otherNewClass').className.split(' ').length == element.className.split(' ').length + 2;
})
.run();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment