HTTPステータスコード
HTTPステータスコード
HTTPステータスコードは、サーバーがリクエストの処理結果を3桁の数字で伝えるものです。
ステータスコードの分類
| 範囲 | 意味 | 例 |
|---|---|---|
| 1xx | 情報 | 100 Continue |
| 2xx | 成功 | 200 OK |
| 3xx | リダイレクト | 301 Moved Permanently |
| 4xx | クライアントエラー | 404 Not Found |
| 5xx | サーバーエラー | 500 Internal Server Error |
よく見るステータスコード
2xx: 成功
| コード | 意味 | 説明 |
|---|---|---|
| 200 | OK | リクエスト成功 |
| 201 | Created | 新しいリソースが作成された |
| 204 | No Content | 成功したがレスポンスボディなし |
Playwrightでの例:
const response = await page.goto('https://example.com');
expect(response.status()).toBe(200);
3xx: リダイレクト
| コード | 意味 | 説明 |
|---|---|---|
| 301 | Moved Permanently | 恒久的な移動 |
| 302 | Found | 一時的な移動 |
| 304 | Not Modified | キャッシュが有効 |
例: ログイン後のリダイレクト
POST /login → 302 Found
Location: /dashboard
Playwrightでの例:
await page.goto('https://example.com/old-page');
// 自動的にリダイレクトされる
await expect(page).toHaveURL('https://example.com/new-page');
4xx: クライアントエラー
| コード | 意味 | 説明 |
|---|---|---|
| 400 | Bad Request | リクエストが不正 |
| 401 | Unauthorized | 認証が必要 |
| 403 | Forbidden | アクセス権限なし |
| 404 | Not Found | ページが見つからない |
Playwrightでの例:
const response = await page.goto('https://example.com/not-exists');
expect(response.status()).toBe(404);
5xx: サーバーエラー
| コード | 意味 | 説明 |
|---|---|---|
| 500 | Internal Server Error | サーバー内部エラー |
| 502 | Bad Gateway | ゲートウェイエラー |
| 503 | Service Unavailable | サービス利用不可 |
E2Eテストでの活用
APIレスポンスの検証
test('API が正常に動作する', async ({ page }) => {
// APIリクエストを監視
const response = await page.waitForResponse('**/api/users');
// ステータスコードを検証
expect(response.status()).toBe(200);
// レスポンスボディを検証
const json = await response.json();
expect(json.users).toHaveLength(10);
});
エラーページのテスト
test('404 ページが表示される', async ({ page }) => {
const response = await page.goto('/not-found-page');
expect(response.status()).toBe(404);
await expect(page.locator('h1')).toContainText('ページが見つかりません');
});
認証エラーのテスト
test('未ログインで403エラー', async ({ page }) => {
const response = await page.goto('/admin/dashboard');
expect(response.status()).toBe(403);
await expect(page).toHaveURL('**/login');
});
検証ツールで確認
- ブラウザで検証ツールを開く(F12)
- Networkタブを選択
- ページをリロード
- Status列でステータスコードを確認
💡 覚えるべき重要なコード
- 200: 成功
- 404: ページが見つからない
- 500: サーバーエラー
テスト設計での考慮点
正常系テスト
// 200 OK の確認
test('ユーザー一覧が取得できる', async ({ page }) => {
const response = await page.waitForResponse('**/api/users');
expect(response.status()).toBe(200);
});
異常系テスト
// 400 エラーの確認
test('不正なデータで400エラー', async ({ page }) => {
// 不正なデータを送信
const response = await page.request.post('/api/users', {
data: { name: '' } // 必須項目が空
});
expect(response.status()).toBe(400);
});
まとめ
| ステータスコード | 覚え方 | テストでの用途 |
|---|---|---|
| 200 | 成功! | 正常系の検証 |
| 404 | 見つからない | エラーページの検証 |
| 500 | サーバーが壊れた | エラーハンドリングの検証 |