びぼーろくっ!

誰かに見せるわけでもないけど、備忘録として。。

mochaの例外テストを組みました。

mocha + power-assertのExceptionテストを実装しました。
前回の記事などでmochaやpower-assertは説明しているので省略します。

//test.js


describe('1件成功+1件例外のテスト', () => {
  before('setup',(done) => {
    target= new Target(); //Test対象メソッドのコンストラクタ作成
    done();
  });
  it('success',(done) => {
    const val = 10;
    //valが数値の為、正常に終了
    const result = target.ValueTwoTimes(val);
    assert(val*2 === result);
    done();
  });

  // 共通クラスの中にAssertExceptionを作成しました。
  // 第一引数にテストメソッド(bindで紐付ける)、
  //第二引数に期待値(エラーオブジェクト)を渡してテストを実行します。
  it('exception', (done) => {
    const val = 'あ';
    let error = new Error('valueは数値でなければなりません!');
    testCommon.AssertException(async.ValueTwoTimes.bind(this,val),error);
    done();
  });
});
import assert from 'power-assert';

export class TestCommon {
 //例外テストを実行し、検証をします。
  AssertException = (callBackFunc,expectedError) => {
    const result = this.exceptionMethodRun(callBackFunc);
    if (result === undefined) assert(result === undefined,'例外処理未発生の為エラー');

    assert(expectedError.message === result.message,'例外処理メッセージ不一致');
  }

 //例外テストを実行しExceptionを返します。
  exceptionMethodRun = (callBackFunc) => {
    let error = undefined;
    try {
      callBackFunc();
    } catch (exception) {
      error = exception;
    }
    return error;
  }
}

const testCommon = new TestCommon();
module.exports = testCommon;
//テスト対象メソッド
export default class Target {
  ValueTwoTimes = (value) => {
    if (typeof value !== 'number') {
      throw new Error('valueは数値でなければなりません!');
    }
    const number = parseInt(value, 10);
    return number * 2;
  }
}
module.exports = Target;

原理は簡単でcallBackで渡されたテスト実行メソッドをtry~catchの中で実行しているだけです。
Exceptionのテストでいちいち記述量が増えてしまうと大変なので作りました。