Karma簡介
Karma是一個簡單的工具俯抖,允許你在多個真實(shí)的瀏覽器上執(zhí)行javascript代碼瓦胎。
但Karma產(chǎn)品的主要目標(biāo)是在測試驅(qū)動開發(fā)(TDD)的項(xiàng)目中,結(jié)合前端測試框架(jasmine、Mocha等)芹缔,使測試更加簡單、快速和輕松示罗。
Karma主要做了兩點(diǎn)
- Karma可以啟動多個瀏覽器芝硬,加載并執(zhí)行指定路徑下的
javascript代碼
- Karma能夠自動監(jiān)控指定路徑下
javascript代碼
的變化。一旦變化绍绘,自動加載執(zhí)行。
如果前面兩點(diǎn)的
Javascript代碼
是測試代碼厂镇,對Karma的目標(biāo)就更容易理解了左刽。
Git start
安裝
Karma需要運(yùn)行在node環(huán)境下,并在NPM包管理下
安裝node環(huán)境
Mac或者Linux欠痴,推薦使用NVM喇辽。windows下,從官方網(wǎng)址下載
注意:Karma目前工作再node0.10,0.12.x,4.x和5.x環(huán)境下
安裝Karma和插件
在本地項(xiàng)目目錄下執(zhí)行下面命令茵臭,安裝Karma以及測試需要的插件(karma-jasmine 結(jié)合測試框架jasmine的插件;karma-chrome-launcher 啟動chrome瀏覽器插件)
#安裝Karma
$ npm install karma --save-dev
#安裝測試項(xiàng)目需要的插件
$ npm install karma-jasmine karma-chrome-launcher --save-dev
karma,karma-jasmine和karma-chrome-launcher包被安裝到項(xiàng)目工作目錄的node_modules目錄下旦委,并且保存他們到package.json的devDependencies依賴配置項(xiàng)中,因此其他開發(fā)者只需要在工作目錄下使用npm install
命令即可得到所有依賴的安裝缨硝。
啟動Karma
#Run Karma:
$ ./node_modules/karma/bin/karma start
或者輸入那么長的啟動命令讓你很煩惱查辩,你可以通過全局安裝karma-cli,以使你可以在任何地方都可以簡單的運(yùn)行Karma
$ npm install -g karma-cli
配置
為了更好的滿足測試宜岛,Karma需要知道你的項(xiàng)目以便測試它,你可以通過配置文件來想Karma描述你的項(xiàng)目
生成配置文件
配置文件能夠由karma init
命令來簡單地生成
$ karma init my.conf.js
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
> Firefox
>
What is the location of your source and test files ?
You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".
Press Enter to move to the next question.
> *.js
> test/**/*.js
>
Should any of the files included by the previous patterns be excluded ?
You can use glob patterns, eg. "**/*.swp".
Press Enter 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 "/Users/vojta/Code/karma/my.conf.js".
配置文件也可以使用CoffeeScript來書寫身弊,事實(shí)上列敲,你執(zhí)行karma init *.conf.coffee
,就可以生成一個CoffeeScript的配置文件
應(yīng)用配置文件啟動Karma
啟動Karma時,把配置文件作為啟動命令的第一個參數(shù)凑术。
默認(rèn)沒有執(zhí)行配置文件參數(shù)的情況下所意,Karma會查看當(dāng)前目錄下是否存在karma.conf.js或者karma.conf.coffee,如果存在則應(yīng)用
# Start karma using your configuration:
$ karma start my.conf.js
我的git start項(xiàng)目
https://github.com/unnKoel/karma-gitstart
參考
http://karma-runner.github.io/0.13/index.html 官網(wǎng)
https://github.com/karma-runner/karma github源