LoginSignup
13
9

More than 5 years have passed since last update.

jasmineで例外をテストする

Last updated at Posted at 2015-03-02

jasmineについて

jasmineはjavascript用のテストフレームワークです。
以下の様な感じでテストを書くことが出来ます。

describe('example', function() {
  it('example', function() {
    expect(1+2).toBe(3);  // 1+2=3であるか...成功
    expect(true).toBeFalsy(); //trueはfalseか...失敗
  });
});

jasmineの記法については、公式サイトやQiitaに詳しい記事がありますので、そちらを御覧ください。
この記事ではjasmineでの例外テストについて記述しています。

jasmineで例外テストを実装する

関数を実行した際に例外が発生するかを.toThrow()でテストできます。

expect(func).toThrow();

また例外の内容を引数に指定すると、エラー内容が正しいかなどもテストできます。

expect(func).toThrow(new Error('This is Error.'));

具体例

Example.js
function Example() {}
Example.prototype.errorFunc = function() {
  throw new Error('エラー');
};
module.exports = Example;
ExampleSpec.js
describe('Exampleテスト', function() {
  var Example = require('Example');
  var example = new Example();

  it('例外の発生を確認', function() {
    expect(example.errorFunc).toThrow();
  });

  it('例外でエラーを投げているのを確認', function() {
    expect(example.errorFunc).toThrow(new Error('エラー'));
  });

});

困ったときは (Actual is not a Function)

テストが動かない場合、expectに渡している関数を実行してしまっている可能性があります。
関数に引数を渡す必要がある場合はfunctionで囲えば解決できます。

Example.js
function Example() {}
Example.prototype.errorFunc = function(argument) {
  if (argument == 'NG') {
    throw new Error('エラー');
  }
};
module.exports = Example;
ExampleSpec.js
describe('Exampleテスト', function() {
  var Example = require('Example');
  var example = new Example();

  it('誤った実装例1', function() {
    expect(example.errorFunc('OK')).toThrow();
    // Actual is not a Function
    // expectの引数には関数を指定する必要がある。
  });
  it('誤った実装例2', function() {
    expect(example.errorFunc('NG')).toThrow();
    // Error: エラー
    // Exampleの例外が発生し、テストが終了してしまう。
  });
  it('正しい実装例1', function() {
    expect(function() {
      example.errorFunc('OK');
    }).toThrow(); // テスト失敗(例外が発生しない)
  });
  it('正しい実装例2', function() {
    expect(function() {
      example.errorFunc('NG');
    }).toThrow(); // テスト成功(例外が発生する)
  });

});

リファレンス

jasmine公式サイト
qiita - Jasmine使い方メモ
stackoverflow - How to write a test which expects an Error to be thrown

13
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
9