在和Firebug团队一起工作的几个月里,我和Jan Odvarko尝试建立一种对JavaScript进行单元测试的方法,这段工作的最后成果是一个叫做FireUnit的Firefox/Firebug扩展。
FireUnit提供了一组JavaScript API,可以进行简单的单元测试,同时把结果显示在Firebug中新增的Tab栏下。
下面就是几个利用FireUnit API进行单元测试的例子(现在我们只提供一些基本的方法,以后就会扩展出更多的方法)。
fireunit.ok( true, "I'm going to pass!" );
fireunit.ok( false, "I'm going to fail!" );
// 比较两个字符串 - 并将差异显示出来
fireunit.compare(
"The lazy fox jumped over the log.",
"The lazy brown fox jumped the log.",
"Are these two strings the same?"
);
// 用正则表达式比较字符串
fireunit.reCompare(
/The .* fox jumped the log./,
"The lazy brown fox jumped the log.",
"Compare a string using a RegExp."
);
// 显示全部结果
fireunit.testDone();
单元测试的结果会显示在Firebug中叫做Test的Tab中(当然为了让FireUnit运行,必须先安装FireBug)。结果页面中的每一项都可以通过展开显示详细信息,包括测试的跟踪记录,以及字符串比较的区别等。

FireUnit也提供了一组方法,用于模拟本地的浏览器事件
var input = document.getElementsByTagName("input")[0];
fireunit.mouseDown( input );
fireunit.click( input );
fireunit.focus( input );
fireunit.key( input, "a" );
And a way of running a batch of test files (each of which would contain a number of individual tests).
fireunit.runTests("test2.html", "test3.html");
// 测试文件的结尾标识
fireunit.testDone();
我们通过这种方式设计了很多Firebug测试用例,尤其针对那些基于网络的功能。
现有的测试用例,只要通过简单的改写,就可以在FireUnit直接显示结果。
jQuery选择符的测试用例是由下面的代码片段组成的:
--------------------------------------------------------------------------------
本文完整内容请参见我的博客:
http://cuimingda.com/2008/12/firefox-firebug-extension-fireunit.html
--------------------------------------------------------------------------------




