8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Jest入門】Errorの評価しよう~toThrow関数~

Last updated at Posted at 2021-09-28

JestでErrorを確認しよう

JestでErrorを評価する際は、toThrow関数を使用します。

toThrow関数

  • 公式ドキュメント
  • 正規表現: エラーメッセージがパターンに マッチする か検証します
  • 文字列:エラーメッセージが文字列を含む か検証します
  • error オブジェクト: エラーメッセージがオブジェクトのmessageプロパティと等しいかを検証します
  • errorクラス: errorオブジェクトがそのクラスのインスタンスであるかを検証します
  • 例外処理をテストする際は無名関数でラップする必要があります
    • その理由は、テスト対象の関数でエラーが発生すると、マッチャーのtoThrow関数が呼ばれる前に関数の実行が停止してしまい、ジェストがエラーを検証できなくなるためです
test("引数がないときにエラーを投げる", () => {
  class Foo {
    constructor({ message }) {
      this.message = message;
    }
  }

  expect(() => new Foo()).toThrow(); // ErrorがThrowされたかチェック
  expect(() => new Foo()).toThrow(TypeError); //型のチェック
  expect(() => new Foo()).toThrow(
    "Cannot destructure property 'message' of 'undefined' as it is undefined."
  ); //エラーメッセージのチェック
});
実行結果
npm test /Users/jest-basic/src/assertion.test.js

> jest-basic@1.0.0 test /Users/jest-basic
> jest "/Users/yoshihiro/jest-basic/src/assertion.test.js"

 PASS  src/assertion.test.js
  ✓ 引数がないときにエラーを投げる (9 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.711 s, estimated 1 s
Ran all test suites matching
8
5
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
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?