0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Jestで `console.warn` をまとめて無効化する方法

0
Posted at

はじめに

テスト実行中に console.warn が大量に出力され、ログが見づらくなることがあります。

そのような場合は、jest.setup.js などの共通セットアップファイルで console.warn を一括でモックすると便利です。

設定例

jest.config.jssetupFilesAfterEnv に指定しているセットアップファイルに、以下を記述します。

beforeEach(() => {
  jest.spyOn(console, "warn").mockImplementation(() => {});
});

afterEach(() => {
  jest.restoreAllMocks();
});

これにより、各テストで console.warn が無効化され、テスト終了後に元の状態へ戻ります。

モジュール読み込み時の警告を抑制したい場合

モジュールの読み込み時に console.warn が実行される場合は、setupFiles の先頭で直接上書きします。

console.warn = () => {};

jest.restoreAllMocks()jest.spyOn() によるモックのみを元に戻すため、モジュール読み込み時の警告まで抑制したい場合は、このように直接代入する方法が有効です。

動作確認環境

  • Jest 29.7.0
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?