FireUnit:基于Firebug的JavaScript单元测试扩展

John Resig最近在他的博客中发表文章John Resig – FireUnit: JavaScript Unit Testing Extension.发布了他与Jan Odvarko合作开发的一款基于Firebug的扩展FireUnit。(Firebug真是越来越强大了……)
简单说来,FireUnit给Firebug增加了一个标签面板,并提供了一些简单的JavaScript API来记录和查看测试。
举例来说:

// Simple true-like/false-like testing
fireunit.ok( true, “I’m going to pass!” );
fireunit.ok( false, “I’m going to fail!” );

// Compare two strings – shows a diff of the
// results if they’re different
fireunit.compare(
“The lazy fox jumped over the log.”,
“The lazy brown fox jumped the log.”,
“Are these two strings the same?”
);

// Compare a string using a regular expression
fireunit.reCompare(
/The .* fox jumped the log./,
“The lazy brown fox jumped the log.”,
“Compare a string using a RegExp.”
);

// Display the total results
fireunit.testDone();

就可以在Firebug中的Test标签面板中看到下图:

fireunit测试

FireUnit还可以模拟触发原生浏览器事件:

// You can also simulate browser events
var input = document.getElementsByTagName(“input”)[0];
fireunit.mouseDown( input );
fireunit.click( input );
fireunit.focus( input );
fireunit.key( input, “a” );

此外,可以批量测试文件(每个文件都含有一些独立测试)

// Or run multiple pages of tests:
fireunit.runTests(“test2.html”, “test3.html”);

// Place at the end of every test file in order to continue
fireunit.testDone();

fireunit批量测试

推荐把测试代码包含在下面的if语句内

if ( typeof fireunit === “object” ) {
//Your code for test
}

如果感兴趣,可以访问Fireunit.org下载并测试(这个网站内就包含了测试代码,安装后即可看到第一张图的内容)
可以在Github上获取源码,得用git而不是svn
Jan也写了一篇文章,可以看看。