Mocha とshould.jsでテストを書いていて例外が起こるテストを書いていて、少し詰まったのでメモ。
例えばhogeというメソッドに空文字列を渡すと例外が生じるというケースのテストを書きたいときに、
foo.hoge('').should.throw();
という書き方をすると、これは誤りで
(function(){ foo.hoge('') }).should.throw();
と書くのが正解。*1
実際に書いてみると下の様な形になる。(確認用なのでテストの中にクラス入れているが、ここは本来requireして呼び出す形。)
これでmochaを実行すると、
$ node_modules/mocha/bin/mocha --reporter spec Foo #sample1 ✓ equal test #sample2 ✓ exception test 2 passing (8ms)
といった形で例外を起こすテストができている。
(Visited 222 times, 1 visits today)