javascript的調試問題,是每個網頁開發人員頭疼的事情,Firefox外掛程式 firebug雖然解決了很多事情,但是當js檔案越來越大的時候,對js的管理變成了越來越棘手的事情。
我們大家都知道對C#的單元測試有一個非常好用的工具 - Nunit,那麼有沒有一個類似的工具,對javascript代碼進行單元測試? 答案是有的,它就是QUnit.
下面用一個簡單的執行個體講解QUnit的操作步驟:
第1步. 在html檔案中加入頭部引用
<link rel="stylesheet" href="css/qunit.css" type="text/css" media="screen" />
<script type="text/javascript" src="js/jquery-1.6.2.js"></script>
<script type="text/javascript" src="js/qunit.js"></script>
第2步. 編寫Html代碼
1 <h1 id="qunit-header">第一個QUnit的例子</h1>
2 <h2 id="qunit-banner"></h2>
3 <div id="qunit-testrunner-toolbar"></div>
4 <h2 id="qunit-userAgent"></h2>
5 <ol id="qunit-tests"></ol>
6 <div id="qunit-fixture">test markup, will be hidden</div>
第3步. 編寫javascript代碼
1 <script>
2 $(document).ready(function(){
3
4 test("a basic test example", function() {
5 ok( true, "this test is fine" );
6 var value = "hello";
7 equal( value, "hello", "We expect value to be hello" );
8 });
9
10 module("Module A");
11
12 test("first test within module", function() {
13 ok( true, "all pass" );
14 });
15
16 test("second test within module", function() {
17 ok( true, "all pass" );
18 });
19
20 module("Module B");
21
22 test("some other test", function() {
23 expect(2);
24 equal( true, false, "failing test" );
25 equal( true, true, "passing test" );
26 });
27
28 });
29 </script>
第4步. 點擊運行Html檔案,查看測試結果
從可以明顯的看出,第4個模組的第一個方法有問題,期望傳回值是false,但是返回了true。
最後總結一下,對javascript代碼的單元測試跟C#單元測試非常類似,使用jquery外掛程式QUnit進行單元測試,幫我們節省了不少指令碼調試的時間。
參考資料見官方網站:http://docs.jquery.com/QUnit
補充一下,我負責開發的網站十裡路採用了大量的QUnit測試方法,大大提高了開發效率。