Created
April 14, 2013 02:39
-
-
Save dz1984/5381151 to your computer and use it in GitHub Desktop.
Using URL path to determine test case with QUnit framework.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
/* | |
* BaseTestCase class | |
*/ | |
function BaseTestCase(name) { | |
this.name = name; | |
this.func = []; | |
} | |
/* | |
* Append the test funciton into the array. | |
*/ | |
BaseTestCase.prototype.addTest = function(testFunc) { | |
if ($.isFunction(testFunc)) | |
this.func.push(testFunc); | |
}; | |
/* | |
* Run the each test function. | |
*/ | |
BaseTestCase.prototype.run = function() { | |
console.log("Begin..." + this.name); | |
$.each(this.func, function(i, testFunc) { | |
test(this.name, testFunc); | |
}); | |
console.log("End..." + this.name); | |
}; | |
/* | |
* BaseTestCaseSuite class | |
*/ | |
function BaseTestCaseSuite() { | |
this.tests = []; | |
this.url = getUrl(); | |
/* | |
* Catch the name from the url . | |
* | |
* Ex. http://localhost/example/about/ => about | |
*/ | |
function getUrl() { | |
var text = window.location.pathname; | |
var re = /^\/\w*\/(\w*)?\/?$/i; | |
var result = re.exec(text); | |
return (typeof (result[1]) == "undefined") ? "" : result[1]; | |
} | |
} | |
/* | |
* Search by name that the BaseTestCase object of array. | |
*/ | |
BaseTestCaseSuite.prototype.getBaseTestCase = function(name) { | |
var result = null; | |
if (this.tests.length >= 1) { | |
$.each(this.tests, function(i, baseTestCase) { | |
if (baseTestCase.name == name) { | |
result = baseTestCase; | |
} | |
}); | |
} | |
return result; | |
} | |
/* | |
* Append the test function into the BaseTestCase instance. | |
*/ | |
BaseTestCaseSuite.prototype.add = function(name, funcs) { | |
var obj = this.getBaseTestCase(name); | |
if (obj == null) { | |
obj = new BaseTestCase(name); | |
this.tests.push(obj); | |
} | |
if ($.isArray(funcs)) { | |
$.each(funcs, function(i, func) { | |
obj.addTest(func); | |
}); | |
} else if ($.isFunction(funcs)) { | |
obj.addTest(funcs); | |
} | |
}; | |
/* | |
* Run the test case depend on the url. | |
*/ | |
BaseTestCaseSuite.prototype.run = function() { | |
var obj = this.getBaseTestCase(this.url); | |
if (obj != null) | |
obj.run(); | |
}; | |
window.BaseTestCaseSuite = BaseTestCaseSuite; | |
})(); | |
var suite = new BaseTestCaseSuite(); | |
suite.add('about', [ function() { | |
ok(suite.url == 'about'); | |
}, function() { | |
ok(1 == "1"); | |
} ]); | |
suite.add('home', [ function() { | |
ok(suite.url == 'home'); | |
}, function() { | |
ok(2 == "2"); | |
} ]); | |
suite.add('books', [ function() { | |
ok(suite.url == 'books'); | |
}, function() { | |
ok(3 == "3"); | |
} ]); | |
suite.run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment