created: 2023-09-14T08:26:00.139Z

jest の test.each でタイムアウトする

たとえば jest でこういう table テストを書くとタイムアウトしてしまう。

test.each([
  [100000, "100,000"],
  [10000000, "10,000,000"],
])("", (i, expected, options = {}) => {
  const actual = maskMoney(i, options);
  expect(actual).toBe(expected);
});

thrown: "Exceeded timeout of 5000 ms for a test while waiting for done() to be called. Add a timeout value to this test to increase the timeout, if this is a long-running test. See https://jestjs.io/docs/api#testname-fn-timeout."

原因

なるほど。

Taking an argument outside of jest.each means it is a done callback: https://jestjs.io/docs/next/api#testname-fn-timeout, and Jest will wait for it to be invoked

jest は test 関数の最後の引数を done 関数として扱い、これが呼ばれるまで待つような挙動になる。

今回の実装ではテーブル部分に [100000, "100,000"] と引数を 2 つしか渡していなかったのに、テスト関数の引数を (i, expected, options = {}) => { のようにして 3 つ定義していた。最後の 1 つにはデフォルト値を設定していたのだが、デフォルト値ではなくこれが done 関数として扱われていた。

計量経済学のための数学
[ad] 計量経済学のための数学
田中 久稔 (Kindle版)