JS单元测试工具Qunit

随着html5的普及和客户端脚本引擎的强大,之前由后端进行的页面渲染和部分业务逻辑逐渐移至到前端,照成前端逻辑和代码迅速复杂化。如果没有一款合适的单元测试工具保证前端单元模块的正确功能,对后期的代码调试和维护会造成很大的麻烦,今天就介绍一款单元测试框架 — Qunit

Qunit刚开始属于jQuery项目,专门用于测试jQuery单元模块。现在已经从jQuery项目中独立出来,你可以在https://github.com/jquery/qunit下载到最新版的Qunit,解压后里面有很多目录,对我们有用的其实只有qunit目录下的qunit.js和qunit.css。

 

下面来个简单的示例:
新建一个html文档,贴入以下代码:

 1 <!DOCTYPE HTML>
 2 <html>
 3     <head>
 4         <!-- 这里引用的是jQuery官网上的Qunit,项目中为了加快下载可以放到本地 -->
 5         <link rel="stylesheet" href="http://code.jquery.com/qunit/git/qunit.css" type="text/css"/>
 6         <script type="text/javascript" src="http://code.jquery.com/qunit/git/qunit.js"></script>
 7     </head>
 8     <body>
 9         <h1 id="qunit-header">QUnit example</h1>
10 
11         <h2 id="qunit-banner"></h2>
12 
13         <div id="qunit-testrunner-toolbar"></div>
14         <h2 id="qunit-userAgent"></h2>
15         <ol id="qunit-tests"></ol>
16         <div id="qunit-fixture">test markup, will be hidden</div>
17         <script>
18             test("a basic test example", function () {
19                 ok(true, "this test is fine");
20                 var value = "hello";
21                 equal(value, "hello", "We expect value to be hello");
22             });
23 
24             module("Module A");
25 
26             test("first test within module", function () {
27                 ok(true, "all pass");
28             });
29 
30             test("second test within module", function () {
31                 ok(true, "all pass");
32             });
33 
34             module("Module B");
35 
36             test("some other test", function () {
37                 expect(2);
38                 equal(true, false, "failing test");
39                 equal(true, true, "passing test");
40             });
41         </script>
42     </body>
43 </html>

用浏览器打开这个html你将会看到如下情况:

1,2,3模块通过测试,4模块出现异常,我们需求预期是false,但却返回了true,未能符合需求,那么下面不用说你也知道该如何了

Qunit的API这里就不在做细致介绍,你可以去http://docs.jquery.com/QUnit下面去找,里面有官方API,绝对详细!祝还在纠结的前端童鞋早日摆脱痛苦

文章作者:前端组-Newton

 

posted on 2012-05-05 09:33  前端组www.qianduanzu.com  阅读(1670)  评论(1编辑  收藏  举报