FireUnit 体验测试驱动的JavaScript开发

FireUnit是一个Firefox扩展,同时也是一个Firebug扩展,这个 扩展提供了一堆API可以帮助你实现JavaScript代码的单元测试,还在Firebug的一堆Tab中再增加一个用于显示测试结果。现在提供的还是 很基本的测试,但是我们要相信这个扩展的潜力,因为它的作者是John Resig和Jan Odvarko,什么?没听过他们?小声问句,你听过JavaScript没有?

【原文标题】http://ejohn.org/blog/fireunit/
【原文作者】John Resig

以下内容是对原文的翻译:

在和Firebug团队一起工作的几个月里,我和Jan Odvarko尝试建立一种对JavaScript进行单元测试的方法,这段工作的最后成果是一个叫做FireUnit的Firefox/Firebug扩展。

FireUnit提供了一组JavaScript API,可以进行简单的单元测试,同时把结果显示在Firebug中新增的Tab栏下。

下面就是几个利用FireUnit API进行单元测试的例子(现在我们只提供一些基本的方法,以后就会扩展出更多的方法)。

// 最简单的true-like/false-like测试
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选择符的测试用例是由下面的代码片段组成的:

if ( typeof fireunit === "object" ) {
QUnit.log = fireunit.ok;
QUnit.done = fireunit.testDone;
}

这个测试用例的结果如下所示:

如果你要开始使用FireUnit,可以先去Fireunit.org看看,顺便下载最新版本。

你也可以到Github去下载源代码

Jan也在自己的博客上写了一篇更加详细的文章,介绍我们如何在Firebug的开发过程中应用FireUnit。

这个项目现在还处在雏形阶段,还有很大的提升空间,我们需要大家的反馈。

原文地址:https://www.cnblogs.com/analyzer/p/1386297.html