简介
随着Javascript框架的繁荣和测试驱动理念的深入人心,Javascript的单元测试框架也日益流行,流行的框架和工具已经不少了,Jsunit,YUI Test,QUnit等等,今天介绍的是
FireUnit,FireUnit是一个基于Firebug的Javascript的单元测试框架,虽然功能不多,但也胜在简单易用。
安装
既然是基于Firefox的插件,所以就需要先安装Firebug1.2以上的版本。FireUnit本身的安装可以通过
http://fireunit.org/fireunit-0.9.xpi 链接完成,重启firefox以后,Firebug就会多了一个Test 标签页(下图中红色标注)。
接下来就可以在Html页面中编写基于FireUnit的单元测试用例了。
FireUnit框架介绍
FireUnit框架比较简单,只要掌握了几个常用的函数就可以进行Javascript的单元测试了。
FireUnit. ok ——将测试结果打印到Firebug的Test 面板。如果某个测试用例测试失败,该测试用例就用红色标注。
/*****************************************/
fireunit.ok(1==1,"1 equals 1");
fireunit.ok(2==1,"2 not equals 1");
fireunit.testDone();
/****************************************/
FireUnit. compare ——对期望值和实际值进行比较,如果两个值不相等就用红色标注测试用例失败。
/*******************************************************************************************/
fireunit.compare(期望值,实际值,"Expected value equals Actual Value");
fireunit.testDone();
/*******************************************************************************************/
FireUnit.reCompare ——通过正则表达式比较两个字符串
/**********************************************/
fireunit.reCompare(
/The .* fox jumped the log./,
"The lazy brown fox jumped the log.",
"Compare a string using a RegExp."
) ;
***********************************************/
FireUnit. runTests ——一起运行多个页面的测试
/**************************************************/
fireunit.runTests("test2.html", "test3.html");
/*************************************************/
Fireunit.testDone——标志测试结束,在用Fireunit.testDone标志测试结束以后,Fireunit就会计算出本次测试的测试汇总情况。
目前Fireunit提供的直接用于测试的API就只有这些了,还有一些辅助测试的API也简单地介绍一下,不过好多API我都没有实际跑过:-)。
FireUnit. log ——打印log
FireUnit. forceHTTP | starts local HTTP server (httpd.js) for network related tests. Also makes sure that cache is cleared. 没做过测试,但感觉挺有用的|.
FireUnit. registerPathHandler | makes possible to register handler for dynamically generated responses. |
FireUnit. id ——相当与document.getElementById
FireUnit. test | inserts tests to execute into a current queue. |
FireUnit. click | 为某个DOM Element模拟Click事件
FireUnit. focus | 为某个DOM Element模拟focus事件
FireUnit. value | sets value of the specified DOM element. |
FireUnit. key | 为某个Dom Element模拟key事件|
FireUnit. panel | 返回到Firebug特定的面板||
FireUnit. privilege | Enables or disables privileges for pages coming from http://localhost:7080 and file:// |
总结
Fireunit还不完善,比如assert语法比较少、比较简单,但已经有一些不错的设计理念和实用的功能了。
参考资料
FireUnit: JavaScript Unit Testing Extension
FireUnit Internals
使用firebug + fireunit做javascript的單元測試