javascript單元測試之jasmine

來源:互聯網
上載者:User

javascript單元測試之jasmine
Hello World: 下面我們就按照demo的結構,建立一個最小測試套件,感受一下這款簡單好用的單元測試。 1. 先建立測試結果頁面,test.html 複製代碼<!DOCTYPE html><html><head><link rel="stylesheet" type="text/css" href="/js/jasmine-2.0.3/jasmine.css"><script type="text/javascript" src="/js/jasmine-2.0.3/jasmine.js"></script><script type="text/javascript" src="/js/jasmine-2.0.3/jasmine-html.js"></script><script type="text/javascript" src="/js/jasmine-2.0.3/boot.js"></script></head><body><h1>jasmine test</h1><script type="text/javascript" src="src.js"></script><script type="text/javascript" src="test.js"></script></body></html>複製代碼jasmine.css是測試結果顯示的外觀控制 jasmine.js就是jasmine.js的測試回合類庫 jasmine-html.js是測試結果顯示的類庫 boot.js是啟動和初始化測試架構的js,  Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project. 網上很多教程是基於2.0之前的版本,會自己寫一段js來啟動jasmine,現在只要載入boot.js就OK啦(不過應該在jasmine.js後面,其他js原始碼之前load) 這三個檔案都會在解壓後的lib裡找到。 src.js 就是我們今天要測試的js代碼,是不是很簡單^_^ function Hello(helloWho){    return "Hello " + helloWho;}test.js就是我們測試案例 複製代碼describe("A suite of basic functions", function() {    var name;     it("Hello World test", function() {        input = "World";        var exp = "Hello World";        expect(exp).toEqual(Hello(input));    });});複製代碼describe塊和it塊都有兩個參數,一個是字串,可以隨便寫,另外一個就是函數。一般來說一個describe用來描述一個套件,包含多個it,每個it用來測試一個function。 當然,describe也是可以嵌套describe的。 在本例中,我們可以看到實際用來檢驗的語句就是“expect().toEqual();”, expect()就是期望得到的結果,toEqual()是它的子方法,表示是否等於它的預期。 expect(3).toEqual(1+2)就是通過單元測試了。

聯繫我們

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