karma で テストしながらカバレッジを取る
karmaでカバレッジを取る
以前書いた記事からkarmaがバージョンアップしており、カバレッジを取得する方法が変わっていました。
カバレッジを取る方法は、preprocessorsとして定義して、その中でプラグインとしてcoverageを呼ぶ方法となっています。
このため、karmaのインストール時に、karma-coverage をインストールします。
karma-coverageのインストール
また、テストにはJasmine、ブラウザとして PhantomJSを使いたいので、以下のようにpackage.jsonを定義します。
{ "devDependencies": { "karma": "~0.12.21", "karma-coverage": "~0.2.5", "karma-jasmine": "~0.1.5", "karma-phantomjs-launcher": "~0.1.4" } }
$ npm install
いろいろなものがインストールされます。
とりあえず対象となるコードを準備
テキトウです。
src\math.js
// 絶対値取得。numが0以上ならそのまま、0以下ならマイナスをかけて返す function abs(num) { if (num >= 0) { return num; } else { return -1 * num; } }
spec\mathspec.js
describe("math suite", function() { it("math.abs spec when num is positive", function() { expect(abs(10)).toEqual(10); }); });
karmaを設定する
おなじみ初期化です。
$ 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 any browsers automatically ? Press tab to list possible options. Enter empty string to move to the next quest ion. > PhantomJS > 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. > src/*.js > spec/*.js > 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. > no
こんなかんじで設定。
PhantomJSの利用と、ソースファイル、テストファイルを読み込ませるだけです。
とりあえずテスト。
$ karma start
INFO [karma]: Karma v0.12.21 server started at http://localhost:9876/ INFO [launcher]: Starting browser PhantomJS INFO [PhantomJS 1.9.7 (Windows 7)]: Connected on socket neyN1RfF24QpB3M5OJL3 with id 7600682 PhantomJS 1.9.7 (Windows 7): Executed 1 of 1 SUCCESS (0.005 secs / 0.004 secs)
OKですね。
カバレッジを取得する設定を行う
karma.conf.js を修正していきます。
カバレッジを取得するように
reporters: ['progress', 'coverage'],
カバレッジ対象のコードを指定
preprocessors: { 'src/*.js' : 'coverage' },
再度
$ karma start
すると、coverageフォルダができます。
こんなかんじ。
└─PhantomJS 1.9.7 (Windows 7) │ index.html │ prettify.css │ prettify.js │ └─src index.html math.js.html
中身はこんなかんじです。
ばっちりですね。