前回の記事「ビルドシステムgulpをCoffeeScriptで使ってみる」ではコンパイル、ファイル監視してコンパイル、クリーンの3つのタスクを作成しました。
今回は、さらにタスクを追加してmochaでテストができるようにしてみます。
gulp-mochaなどの追加
gulpでmochaを使うにはgulp-mochaを入れるだけでよいです。
$ npm install --save-dev gulp-mocha should
テストをBDDスタイルで書きたいので、ついでにshouldも入れています。
テストタスクの追加
まず、gulpfileでモジュールを宣言します。
# test tools mocha = require 'gulp-mocha'
そして、テストタスクを追加するだけです。
# test
gulp.task 'test', ['script'], ->
gulp.src ['lib/*.js', 'test/*.coffee']
.pipe mocha {reporter: 'spec'}
テストの追加
試しにテストを書いてみます。
test/sample.unit.coffeeは次のようなテストです。
require 'should'
foo = require('../lib/sample');
describe 'foo()', ->
it 'は引数ありなら正負を逆にした値を返す', ->
foo(9).should.equal -9
foo(-3).should.equal 3
it 'は0なら0を返す', ->
foo(0).should.equal 0
it 'は引数なしなら0を返す', ->
foo().should.equal 0
それに対するsrc/sample.lsは次のようにしました。
!function foo a = 0
return -a
if module? and module.exports?
module.exports = foo
これで実行すると、次のようにテストが実行されました。
$ gulp test
[gulp] Using file /Users/safx/src/mantle-gen/gulpfile.js
[gulp] Working directory changed to /Users/safx/src/mantle-gen
[gulp] Running 'script'...
[gulp] Finished 'script' in 23 ms
[gulp] Running 'test'...
foo()
✓ は引数ありなら正負を逆にした値を返す
✓ は0なら0を返す
✓ は引数なしなら0を返す
3 passing (3ms)
[gulp] Finished 'test' in 40 ms
おわりに
gulpfileにタスクを追加してmochaでテストができるようにしました。

0 件のコメント:
コメントを投稿
注: コメントを投稿できるのは、このブログのメンバーだけです。