使用QUnit對javascript指令碼進行單元測試

來源:互聯網
上載者:User

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測試方法,大大提高了開發效率。
  

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.