因为现有的javascript单元测试框架在测试异步方法都有这样那样的问题,所以不得不自己动手写了一个,这个框架代码量很小,但简单灵活,很好扩展,它的特性有:
1、可测试同步异步方法。
2、测试结果页面可定制。
3、可自己扩展assertion方法。
项目地址: http://code.google.com/p/flexible-javascript-unittest/
使用示例:
1.基础用法
window.onload = function(){ var test1 = new testcase("my first test", { setup: function(){this.val = "abc";}, teardown: function(){this.val = null;alert("test completed.");}, test_get_name: function(){ this.assert_equal("abb", this.val, "test get name"); this.assert_not_equal("abb", this.val); } }; test1.run(); }
2.测试异步方法
function xhttp(url, callback) { if (typeof XMLHttpRequest != 'undefined') { httpRequest = new XMLHttpRequest(); } else if (typeof ActiveXObject != 'undefined') { httpRequest = new ActiveXObject('Microsoft.XMLHTTP'); } httpRequest.open('GET', url, true); httpRequest.onreadystatechange = function () { if (httpRequest.readyState == 4) { callback(httpRequest.responseText); } }; httpRequest.send(null); } window.onload = function(){ var test1 = new testcase("my firest test", { setup: function(){this.val = "abc";}, teardown: function(){this.val = null;alert("test completed.");}, test_get_name: function(){ this.assert_equal("abb", this.val, "test get name"); this.assert_not_equal("abb", this.val); }, test_get_name1: function(){ this.assert(false); throw "this is an exception"; }, async_test_google: function() { var self = this; xhttp("http://www.google.com", function(html){ self.assert(html.indexOf("google") > 0); self.complete(); }); }, async_test_yahoo: function() { var self = this; xhttp("http://www.yahoo.com", function(html){ self.assert(html, "google"); self.assert(html.indexOf("yahoo") > 0); self.complete(); }); } }); test.run(); }
faq:
1.如何测试测试异步方法?
两个要求:一、方法必须是以async_test开头
二、在异步方法结束后调用this.complete()方法。
2.如何定制输出界面?
新建一个ui类,并实现其中方法:
var myui = function(test){ this.test = test; this.on_inited = function(){}; this.on_assert_success = function(assert_name, method_name){}; this.on_assert_failed = function(assert_name, method_name, default_message, message){}; this.on_error = function(method_name, e){}; this.on_completed = function(test){}; }
然后通过
new testcase("name", {...}, new myui());
或者
var test = new testcase...
test.ui = new myui();
把这个ui对象与testcase绑定起来。
3、支持的断言方法
assert
assert_equal
assert_not_equal
assert_null
assert_not_null
assert_match
assert_not_match
4、如何扩展assertion方法?
为 testcase_assertion添加方法即可
testcase_assertion.prototype.assert_blabla = function(...) { //var default_msg = "actual is not null"; //var bool = (actual == null); //this.do_assert("assert_null", bool, msg, default_msg); };