1、斷言
單元測試的核心部分是斷言。所謂斷言,則是表達程式設計人員對於系統應達到狀態的一種預期。javascript中沒有提供斷言,但我們可以自己設計這個方法。
function assert(msg, value) {if (!value) {throw new Error(msg);}assert.count++;return true;}assert.count = 0;
這裡,assert函數只是見車它的第二個蠶食是否為真(除了false、null、undefined、0、“”、和NaN之外的任何值)。如果為真,就把斷言計數器加1,否則就拋出錯誤。
2、紅和綠
在單元測試中,通常分別用“紅” 和 "綠” 來表示 “失敗” 和 “成功“ 。因為讓測試變紅或變綠,會使得結果更加容易理解。下面提供了一個簡化的輸出函數,使用DOM來顯示顏色的訊息
function output(text, color) {var p = document.createElement("p");p.innerHTML = text;p.style.color = color;document.body.appendChild(p);}
3、測試函數
由於測試失敗時assert函數只是簡單地拋出錯誤,所以我們沒法知道出錯的測試之後是失敗還是成功。所以,我們可以把測試組織成測試函數。如此一來,每個測試函數就只執行一個單元,但可以調用一個或多個斷言。
function TestCase(name, tests) {assert.count = 0;var successful = 0;var testCount = 0;var hasSetup = typeof tests.setUp == "function";var hasTeardown = typeof tests.tearDown == "function";for (var test in tests) { //只執行以test開頭的函數if (!/^test/.test(test)) {continue;}testCount++;try {if (hasSetup) {tests.setUp(); // 執行設定函數}tests[test](); // 執行測試函數output(test, "#0c0"); // 在頁面輸出綠色if (hasTeardown) {tests.tearDown(); // 執行拆除函數}successful++;} catch (e) {output(test + " failed: " + e.message, "#c00"); // 在頁面輸出紅色與錯誤資訊}}var color = successful == testCount ? "#0c0" : "#c00";output("<strong>" + testCount + " tests, " +(testCount - successful) + " failures</strong>", color);}
下面是具體的使用方法,這個測試將會測試失敗,因為arr的長度是5而不是7。
TestCase("assertTest", {setUp: function () {this.arr = [1, 2, 3, 4, 5];},"test arr length": function() {assert("arr length is 7", this.arr.length === 7);},tearDown: function () {}});
by、junjun16818