Mocha & should.js で例外が生じるケースのテストを書く

Mochashould.jsでテストを書いていて例外が起こるテストを書いていて、少し詰まったのでメモ。

例えばhogeというメソッドに空文字列を渡すと例外が生じるというケースのテストを書きたいときに、

foo.hoge('').should.throw();

という書き方をすると、これは誤りで

(function(){ foo.hoge('') }).should.throw();

と書くのが正解。*1

実際に書いてみると下の様な形になる。(確認用なのでテストの中にクラス入れているが、ここは本来requireして呼び出す形。)

// test/foo.test.js
var should = require('should');

function Foo() {
    return {
        hoge: function(val) {
            if (val == '') {
                throw new Error('fail');
            }

            return val;
        }
    };
}

var foo = Foo();

describe('Foo', function() {
    describe('#sample1', function() {
        it('equal test', function(){
            foo.hoge('bar').should.equal('bar');
        });
    });

    describe('#sample2', function() {
        it('exception test', function(){
            (function(){ foo.hoge('') }).should.throw();
        });
    });

});

これでmochaを実行すると、

$ node_modules/mocha/bin/mocha --reporter spec


  Foo
    #sample1
      ✓ equal test
    #sample2
      ✓ exception test


  2 passing (8ms)

といった形で例外を起こすテストができている。

*1:https://github.com/visionmedia/should.js/#throw-and-throwerror に書いてあるのだが....