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)就是通過單元測試了。