GruntではHeadlessなユニットテストを行うための Qunit があります。しかし、個人的にはRSpec風に記述できる Jasmine の方が読みやすいので、Jasmineでのユニットテスト環境を構築してみました。
まず、Grunt Jasmine runner をインストール
$ cd /your-project $ npm install grunt $ npm install grunt-jasmine-runner
PhantomJSがない場合はBrewでいれておく
$ brew install phantomjs
自身のgrunt.jsファイルに追加
// Jasmine jasmine: { // テストするためのソースファイル src : 'path/to/project/*.js', // ヘルパーファイル helpers : 'specs/helpers/*.js', // ジャスミンのテストが含まれているspecファイル specs : 'specs/**/*spec.js', // テストが破棄されるまでのタイムアウト時間 timeout : 10000, // テンプレート template : 'path/to/project/custom.tmpl', // ポート番号(デフォルト8888) port :8686 // junit xmlの出力先 junit : { output : 'junit/' }, // phantomjsのオプション phantomjs : { 'ignore-ssl-errors' : true } } grunt.loadNpmTasks('grunt-jasmine-runner');
という感じで、テストを走らせてみる
$ grunt jasmine $ Running "jasmine" task Testing jasmine specs via phantom 3 specs, 0 failures in 0.012s.
また、ブラウザで実行するときは
'jasmine-server' : { // デフォルトのブラウザを自動で開く(デフォルトtrue) browser :true }
をgrunt fileに追加して
$ grunt jasmine-server Running "jasmine-server" task Run your tests at http://127.0.0.1:8888/_SpecRunner.html
で実行できます。
watchオプションでファイルの保存を監視をしているなら、タスクに加えておけばテストも自動化できます。
watch: { coffee: { files: [ 'path/to/project/*.js' ], tasks: 'clean:js coffee jasmine' } }
という感じすれば、ファイル保存の後に、coffeeコンパイルそしてテスト という感じに自動化されて良さそうですね。