@peccul is peccu

(love peccu '(emacs lisp cat outdoor bicycle mac linux coffee))

JestのtoBeThrowは関数で確かめる

タイトルの通りですが。

関数呼び出しの前に () =>をつけましょう。

継承されることを想定しているクラスでNotImplementedなエラーを投げ、それをテストしようとしていた。
次の例だと呼び先のThrowをjestが失敗扱いする。

let someThrowFunction = (someArgs) => {
  throw new Error('not implemented');
};

test('throw as error', () => {
  expect(someThrowFunction(someArgs)).toBeThrow();
});

f:id:peccu:20190105170221p:plain

解決策

関数呼び出しを関数に入れなければならない。もしくは関数そのものを渡す。
言われてみればドキュメントもその旨書いてあるしサンプルもその書き方になってる。

Use .toThrow to test that a function throws when it is called.

Expect · Jest

その関数が呼ばれるとthrowすることをテストする。なので呼んでしまうとそれは戻り値のテストになってしまう。

こんな感じで関数で囲むか関数そのものを渡しましょう。

test('throw in function', () => {
  expect(() => someThrowFunction(someArgs)).toBeThrow();
});
test('throw from function', () => {
  expect(someThrowFunction).toBeThrow();
});

environment

  • .babelrc
{
  "presets": ["@babel/preset-env"],
  "plugins": [
    [
      "@babel/plugin-transform-runtime",
      {
        "regenerator": true
      }
    ]
  ]
}
  • package.json
...
  "scripts": {
    "test": "jest"
  },
  "devDependencies": {
    "@babel/core": "^7.2.2",
    "@babel/plugin-transform-runtime": "^7.2.0",
    "@babel/preset-env": "^7.2.3",
    "@babel/runtime": "^7.2.0",
    "babel-core": "^7.0.0-bridge.0",
    "babel-jest": "^23.6.0",
    "jest": "^23.6.0"
  },
...