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?

はじめに

こんにちは。アメリカ在住で独学エンジニアを目指している Taira です。

テストを書いていると「なんでテストが通らないんだろう?」という瞬間が必ずありますよね。そんなときに役立つのが screen.debug() です。React Testing Library が提供しているこの関数を使うと、現在の DOM の状態をそのまま出力できるので、デバッグ効率が一気に上がります。


screen.debug() とは?

  • React Testing Library が提供するユーティリティ関数。
  • 現在の仮想 DOM をコンソールに整形して表示してくれる。
  • console.log で中途半端に出力するよりも圧倒的に見やすく、テストのデバッグが楽になります。

使い方の例

import { render, screen } from '@testing-library/react';
import App from './App';

test('renders hello text', () => {
  render(<App />);
  screen.debug(); // ←ここでDOMを出力して確認
  expect(screen.getByText(/hello/i)).toBeInTheDocument();
});

実行するとテスト時点での DOM が CLI に出力されます。特に「思った要素がレンダリングされていない」「クラス名や属性が違う」などの確認に役立ちます。


出力のイメージ

<body>
  <div>
    <h1>Hello World</h1>
    <button>Click me</button>
  </div>
</body>

よくある使いどころ

  • 要素が見つからないとき
    getByText がエラーになるときに、そもそも文字が DOM に存在するかチェックできる。

  • 属性やクラスが合っているか確認したいとき
    例えば data-testid をつけ忘れていた、className が意図したものと違っていた、などの発見が早い。

  • 条件分岐で UI が切り替わるケース
    if/else のレンダリング結果を即座に確認できる。


オプション引数

screen.debug(element, maxLength, options) という形で指定可能です。

  • element: 特定の要素だけを表示
  • maxLength: 出力する文字数制限(デフォルト7000文字)
  • options: highlight: true を渡すと getBy... で失敗した箇所を強調表示

例:

screen.debug(undefined, 20000, { highlight: true });

まとめ

  • screen.debug() はテストの強い味方。
  • 「テストが通らない」→「とりあえず debug してみる」の流れを習慣にすると効率が上がります。
  • シンプルですが、実務でも頻繁に使う小技として覚えておくとかなり便利です。
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?