問題一覧に戻る
上級テストとベストプラクティス
問題99: 単体テスト基礎

コンポーネントテストのためのReact Testing Library基礎を学びます。ユーザーがコンポーネントと対話する方法に似たテストを書きます。renderでコンポーネントをマウント、screenクエリで要素を検索、fireEventでユーザー操作をシミュレートします。実装の詳細ではなく動作のテストに焦点を当てます。

import React, { useState } from 'react';
import { render, screen, fireEvent } from '@testing-library/react';

function Counter() {
const [count, setCount] = useState(0);

return (
<>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>+</button>
</>
);
}

{/* テストスイート */}
describe('Counter', () => {
test('renders initial count', () => {
{/* コンポーネントをレンダー */}
();

{/* テキストで要素を検索 */}
const text = screen.('Count: 0');
expect(text).toBeInTheDocument();
});

test('increments on click', () => {
render(<Counter />);

{/* ボタン要素を取得 */}
const button = screen.getByText('');

{/* クリックイベントを発火 */}
.click(button);

expect(screen.getByText('Count: 1')).toBeInTheDocument();
});
});