Javascript單元測試Unit Testing之QUnit
QUnit是一個基于JQuery的單元測試Unit Testing 框架。雖然是基于JQuery但用來測試純Javascript代碼。
用來運行Javascript單元測試用例的html頁面是這樣的:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>QUnit test runner</title> <link rel="stylesheet" href="lib/qunit-1.10.0.css"> </head> <body> <div id="qunit"></div> <div id="qunit-fixture"></div> <script src="lib/qunit-1.10.0.js"></script> <!--test code goes here--> </body> </html> |
假設我們有如下簡單的javascript代碼simpleMath.js,實現基本的數學操作,階乘,平均數。
SimpleMath = function() { }; SimpleMath.prototype.getFactorial = function (number) { if (number < 0) { throw new Error("There is no factorial for negative numbers"); } else if (number == 1 || number == 0) { // If number <= 1 then number! = 1. return 1; } else { // If number > 1 then number! = number * (number-1)! return number * this.getFactorial(number-1); } } SimpleMath.prototype.signum = function (number) { if (number > 0) { return 1; } else if (number == 0) { return 0; } else { return -1; } } SimpleMath.prototype.average = function (number1, number2) { return (number1 + number2) / 2; } |
如對getFactorial函數,我們可以編寫以下3種測試用例:
正數,零,負數
// Factorial testing module module("Factorial", { setup: function() { this.simpleMath = new SimpleMath(); }, teardown: function() { delete this.simpleMath; } }); test("calculating factorial for a positive number", function() { equal(this.simpleMath.getFactorial(3), 6, "Factorial of three must equal six"); }); test("calculating factorial for zero", function() { equal(this.simpleMath.getFactorial(0), 1, "Factorial of zero must equal one"); }); test("throwing an error when calculating the factorial for a negative number", function() { raises(function() { this.simpleMath.getFactorial(-10) }, "There is no factorial for negative numbers ..."); }); |
上面的代碼中,module中有setup, teardown可以讓我們事前事后做一些操作,使用斷言equal期望3的階乘結果是6,如果您有接觸過Java或C#平臺的單元測試,應該不能理解。然后我們把2個js腳本文件引入到上面html中
<script src="src/simpleMath.js"></script>
<script src="tests/simpleMathTest.js"></script>
最終我們在瀏覽器中打開這個html,結果也就是顯示出來了。
如上圖,我們看到7個測試用例,全部有通過了,點擊前2個用例,顯示出斷言的結果。常見的斷言還有ok( truthy [, message ] ), deepEqual( actual, expected [, message ] ),如下是ok:
ok(true, "true passes");
ok(4==4, "4 must equal 4");
ok("some string", "Non-empty string passes");
QUnit也有支持異步ajax的測試方法asyncTest,由于篇幅有限,在這兒不多介紹了。寫這篇文章的時候,QUnit是v1.14.0版本了。未來可能還有新版本。更多內容,請可以參考API文檔。
希望對您軟件開發有幫助。