Node.jsでBDD / TDDするときに必要なモジュール
テストを書くときにも便利なモジュールが沢山あります。
メインで使うのはJasmineとかも良く使われてるみたいだけど、visionmedia製のmochaが扱いやすい。
mocha上では色んなアサーション系モジュールが使える。
(調べたらAssertionは断言、断定するって意味だた。なるほど。)
基本はNode.js自体で持っているAssertで良いハズなんだけども、should.jsとかexpect.jsとかchaiとか色んなものがある。
それぞれはこんなふうに書ける。(requireとかは省略)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe('test description.', function() { | |
it('fails on a invalid key', function() { | |
var hoge = 'hoge'; | |
assert.equal(hoge, 'hoge'); | |
'hoge'.should.equal(hoge); | |
chai.assert.equal(hoge, 'hoge'); | |
expect(hoge).to.be('hoge'); | |
}) | |
}) |
should => きっと〜だろう。
expect => 〜だと予想する。
みたいに、こうあって欲しいなという英語が使われていて、英語がわかれば使いやすい作りになってる。(''.should.be.empty => ""は空でなければならない。みたいな)
今使っているのはshould.jsをベースにしたexpect.js。
クロスブラウザ対応してたりどんな環境でも特に問題なく動くそうだ。
expect.jsの使い方。
色んな使い方があるけど殆どはドキュメント見ればそのとおりに動く。
基本的な所だと
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// be / equal (===) | |
expect(1).to.be(1); | |
// a : (typeof) | |
expect(3).to.be.a('number'); | |
expect([]).to.be.an('array'); | |
expect({}).to.be.an('object'); | |
// a はコンストラクタ指定も出来る | |
expect(5).to.be.a(Number); | |
expect([]).to.be.an(Array); | |
expect({}).to.be.an(Object); | |
// empty | |
expect({}).to.be.empty(); | |
expect({a:1}).to.not.be.empty(); | |
aはanにも出来るくらい自然言語に近く扱えるらしい。英語出来ないと恩恵ないけどw
ちょっと詰まったのでメモ。
複数のErrorをthrowしちゃうメソッドをチェックするときはちょっと工夫が必要だった。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function targetMethod(param) { | |
if(param === null || param === undefined) { | |
throw new Error('param is empty.'); | |
} | |
if(typeof param !== 'string') { | |
throw new Error('param must be a Number.'); | |
} | |
console.log(param); | |
} | |
// closure | |
var result1 = function() { | |
var _badParam = null; | |
targetMethod(_badParam); | |
}; | |
var result2 = function() { | |
var _badParam = 'string'; | |
targetMethod(_badParam); | |
} | |
// throwError | |
expect(result1).to.throwError(); | |
// Check the error message using a regex. | |
expect(result1).to.throwError(/param is empty/); | |
expect(result2).to.throwError(/param must be a Number./); |
expect(targetMethod(null)).to.throwError(/param is empty/);
とか書きたくなるけど、これだとtargetMethodが実行されて普通にErrorがthrowされてテストが止まってしまう。
それを回避するためにクロージャを使ってErrorの出し分けをやってみたら上手く行ったわけです。
ただテストに慣れてないだけっていう噂もあるけど、JavaScriptでテストを書くときはexpect.js使って大体のことが出来そうです。
間違ってたり、もっと良い使い方、書き方があれば勉強中なので教えてください〜〜。
よろしくお願い致します。
0 件のコメント:
コメントを投稿