隨著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