相信你們都知道測試的必要性,測試先行的概念。不過,寫了這麼多年的代碼,除了以前用java的時候寫過一些測試用例,還真的不多寫過前端的測試用例,或者作一些自動化測試。感受作單元測試仍是頗有必須的,它能幫助你整理思路,換個角度思考問題,發現bug。最近正好研究一下,以前瞭解到jasmine是作js單元測試的利器,karma是用來自動化運行分析統計單元測試的,結合karma-coverage還能統計代碼覆蓋率,這麼牛的神器,必定要試一試。另外最後會介紹另一個端到端的測試神器protractor,不過目前只能測試angular的應用。javascript
轉載請註明出處:http://www.haomou.net/2015/03/10/2015_karma_jasmine/css
Karma是Testacular的新名字,在2012年google開源了Testacular,2013年Testacular更名爲Karma。Karma是一個讓人感到很是神祕的名字,表示佛教中的緣分,因果報應,比Cassandra這種名字更讓人猜不透!html
Karma是一個基於Node.js的JavaScript測試執行過程管理工具(Test Runner)。該工具可用於測試全部主流Web瀏覽器,也可集成到CI(Continuous integration)工具,也可和其餘代碼編輯器一塊兒使用。這個測試工具的一個強大特性就是,它能夠監控(Watch)文件的變化,而後自行執行,經過console.log顯示測試結果。前端
官網:https://karma-runner.github.iojava
安裝nodejs,注意相關版本要求node
安裝karma和相關插件,推薦的方法是在項目目錄安裝karma和相關插件git
1
2
3
4
5
|
# Install Karma:
$ npm install karma --save-dev
# Install plugins that your project needs:
$ npm install karma-jasmine karma-chrome-launcher --save-dev
|
上面的命令會安裝karma, karma-jasmine 和 karma-chrome-launcher 到node_modules目錄,同時將配置保存到package.json中。接着能夠運行karmaangularjs
1
2
|
# Run Karma:
$ ./node_modules/karma/bin/karma start
|
注意,直接運行karma是不行的,確定會報錯,須要用上面的方法運行。若是想直接用karma命令,須要安裝karma-cli,以下所示:github
1
|
$ npm install -g karma-cli
|
而後你就能夠直接運行karma命令了。web
咱們執行
1
2
3
|
./node_modules/karma/bin/karma start
INFO [karma]: Karma v0.10.2 server started at http://localhost:9876/
INFO [Chrome 28.0.1500 (Windows 7)]: Connected on socket nIlM1yUy6ELMp5ZTN9Ek
|
能夠看到karma會自動打開瀏覽器,界面以下:
執行:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
./node_modules/karma/bin/karma init
Which testing framework do you want to use ?
Press tab to list possible options. Enter to move to the next question.
> jasmine
Do you want to use Require.js ?
This will add Require.js plugin.
Press tab to list possible options. Enter to move to the next question.
> no
Do you want to capture a browser automatically ?
Press tab to list possible options. Enter empty string to move to the next question.
> Chrome
>
What is the location of your source and test files ?
You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".
Enter empty string to move to the next question.
>
Should any of the files included by the previous patterns be excluded ?
You can use glob patterns, eg. "**/*.swp".
Enter empty string to move to the next question.
>
Do you want Karma to watch all the files and run the tests on change ?
Press tab to list possible options.
> yes
Config file generated at "D:\workspace\javascript\karma\karma.conf.js".
|
經過這種命令行的形式,咱們就成功配置了karma自動化運行腳本。
後面能夠根據須要作修改。
jasmine是爲javascript提供的行爲驅動的測試開發框架,它不依賴於瀏覽器,DOM,或者其餘javascript框架,能夠爲web項目,node項目或者其餘運行js的項目寫單元測試。
使用文檔api介紹:http://jasmine.github.io/2.0/introduction.html
咱們假設在當前目錄,按照上面的方法安裝了karma,(須要注意的是上面安裝karma的時候已經安裝了jasmine),而後咱們作個測試。
1
2
3
|
function reverse(name){
return name.split("").reverse().join("");
}
|
1
2
3
4
5
|
describe("A suite of basic functions", function() {
it("reverse word",function(){
expect("DCBA").toEqual(reverse("ABCD"));
});
});
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: ['*.js'],
exclude: ['karma.conf.js'],
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
captureTimeout: 60000,
singleRun: false
});
};
|
剛纔經過命令行的方式生成的配置文件和上面的可能有所不一樣,做參考。
1
2
3
4
5
6
7
8
9
10
11
|
./node_modules/karma/bin/karma start karma.conf.js
INFO [karma]: Karma v0.10.2 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
WARN [launcher]: The path should not be quoted.
Normalized the path to C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
INFO [Chrome 28.0.1500 (Windows 7)]: Connected on socket bVGffDWpc1c7QNdYye_6
INFO [Chrome 28.0.1500 (Windows 7)]: Connected on socket DtTdVbd4ZsgnMQrgye_7
Chrome 28.0.1500 (Windows 7): Executed 1 of 1 SUCCESS (3.473 secs / 0.431 secs)
Chrome 28.0.1500 (Windows 7): Executed 1 of 1 SUCCESS (0.068 secs / 0.021 secs)
TOTAL: 2 SUCCESS
|
會自動打開瀏覽器
安裝代碼覆蓋率插件karma-coverage
1
|
~ D:\workspace\javascript\karma>npm install karma-coverage
|
修改karma.conf.js配置文件
1
2
3
4
5
6
|
reporters: ['progress','coverage'],
preprocessors : {'src.js': 'coverage'},
coverageReporter: {
type : 'html',
dir : 'coverage/'
}
|
啓動karma start,在工程目錄下面找到index.html文件,coverage/chrome/index.html
打開後,咱們看到代碼測試覆率綠報告
覆蓋率是100%,說明咱們完整了測試了src.js的功能。
接下來,咱們修改src.js,增長一個if分支
1
2
3
4
|
function reverse(name){
if(name=='AAA') return "BBB";
return name.split("").reverse().join("");
}
|
再看覆蓋率報告,
protractor是專爲angular應用設計的端到端的測試框架,它直接在瀏覽器中運行,模擬相似於人在實際環境中的交互操做來測試。
官網主頁:http://angular.github.io/protractor/#/
執行
1
|
npm install -g protractor
|
改命令會安裝protractor 和 webdriver-manager兩個命令行工具,能夠執行
1
|
protractor --version
|
來測試是否安裝成功。而後經過執行
1
|
webdriver-manager update
|
上面的命令會下載必要的支持組建,而後能夠經過
1
|
webdriver-manager start
|
來啓動一個server,咱們運行的protractor test會運行在這個server上,能夠在 http://localhost:4444/wd/hub 地址查看server的運行狀態。
1
2
3
4
5
6
7
8
9
10
11
12
|
describe('angularjs homepage todo list', function() {
it('should add a todo', function() {
browser.get('http://www.angularjs.org');
element(by.model('todoText')).sendKeys('write a protractor test');
element(by.css('[value="add"]')).click();
var todoList = element.all(by.repeater('todo in todos'));
expect(todoList.count()).toEqual(3);
expect(todoList.get(2).getText()).toEqual('write a protractor test');
});
});
|
其中describe和it使用的是jasmine的語法,browser是protractor提供的全局對象,用於執行瀏覽器級別的任務,好比導航加載頁面能夠用browser.get方法。
1
2
3
4
|
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['todo-spec.js']
};
|
這個配置文件主要告訴protractor測試的文件和服務器的地址,默認使用chrom瀏覽器。
1
|
protractor conf.js
|
你會看見會自動打開瀏覽器,跳轉到todolist頁面,而後關閉頁面。