javascript 編寫單元測試架構

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.