# IOS Snapshot Test

> iOS スナップショットテスト支援スキル

- Skill: `caphtech/ios-snapshot-test` (Agent Skill)
- Install (CLI): `npx get-skill add caphtech/ios-snapshot-test`
- Raw SKILL.md: https://api.skillmd.com/api/skills/caphtech/ios-snapshot-test/raw
- Safety review: pending (external: skill-scanner PASS, skillspector PASS)
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: CAPHTECH (https://skillmd.com/u/caphtech)
- Updated: 2026-09-22
- Page: https://skillmd.com/skills/caphtech/ios-snapshot-test

---


# iOS スナップショットテスト支援スキル

swift-snapshot-testingを使用したUIスナップショットテストをガイドする。

## swift-snapshot-testing

### 導入

```swift
// Package.swift
dependencies: [
    .package(url: "https://github.com/pointfreeco/swift-snapshot-testing", from: "1.15.0")
]

// テストターゲットに追加
.testTarget(
    name: "MyAppTests",
    dependencies: [
        .product(name: "SnapshotTesting", package: "swift-snapshot-testing")
    ]
)
```

### 基本的なテスト

```swift
import XCTest
import SnapshotTesting
@testable import MyApp

final class ProfileViewSnapshotTests: XCTestCase {
    
    // 初回・意図的な変更時の記録は withSnapshotTesting(record: .all) { ... } でラップして実行
    
    func testProfileView() {
        let view = ProfileView(user: .mock)
        
        assertSnapshot(of: view, as: .image)
    }
    
    func testProfileView_darkMode() {
        let view = ProfileView(user: .mock)
        
        assertSnapshot(of: view, as: .image(traits: .init(userInterfaceStyle: .dark)))
    }
    
    func testProfileView_largeText() {
        let view = ProfileView(user: .mock)
        
        assertSnapshot(
            of: view,
            as: .image(traits: .init(preferredContentSizeCategory: .accessibilityLarge))
        )
    }
}
```

## SwiftUIビューのテスト

### ホスティングコントローラー経由

```swift
import SwiftUI
import SnapshotTesting

final class SwiftUISnapshotTests: XCTestCase {
    
    func testContentView() {
        let view = ContentView()
        let controller = UIHostingController(rootView: view)
        
        // サイズを指定
        controller.view.frame = CGRect(x: 0, y: 0, width: 375, height: 812)
        
        assertSnapshot(of: controller, as: .image)
    }
    
    func testButtonStyles() {
        let view = VStack(spacing: 16) {
            Button("Primary") {}
                .buttonStyle(PrimaryButtonStyle())
            
            Button("Secondary") {}
                .buttonStyle(SecondaryButtonStyle())
            
            Button("Destructive") {}
                .buttonStyle(DestructiveButtonStyle())
        }
        .padding()
        
        let controller = UIHostingController(rootView: view)
        controller.view.frame = CGRect(x: 0, y: 0, width: 300, height: 200)
        
        assertSnapshot(of: controller, as: .image)
    }
}
```

### カスタムスナップショット戦略

```swift
extension Snapshotting where Value: SwiftUI.View, Format == UIImage {
    static func swiftUIImage(
        drawHierarchyInKeyWindow: Bool = false,
        precision: Float = 1,
        perceptualPrecision: Float = 1,
        size: CGSize? = nil,
        traits: UITraitCollection = .init()
    ) -> Snapshotting {
        return Snapshotting<UIViewController, UIImage>.image(
            drawHierarchyInKeyWindow: drawHierarchyInKeyWindow,
            precision: precision,
            perceptualPrecision: perceptualPrecision,
            size: size,
            traits: traits
        ).pullback { view in
            UIHostingController(rootView: view)
        }
    }
}

// 使用例
func testCustomStrategy() {
    let view = MyCustomView()
    
    assertSnapshot(
        of: view,
        as: .swiftUIImage(size: CGSize(width: 320, height: 480))
    )
}
```

## 状態別テスト

### ローディング・エラー状態

```swift
final class StateSnapshotTests: XCTestCase {
    
    func testUserList_loading() {
        let view = UserListView(state: .loading)
        assertSnapshot(of: view, as: .swiftUIImage())
    }
    
    func testUserList_loaded() {
        let view = UserListView(state: .loaded(users: User.mockList))
        assertSnapshot(of: view, as: .swiftUIImage())
    }
    
    func testUserList_empty() {
        let view = UserListView(state: .loaded(users: []))
        assertSnapshot(of: view, as: .swiftUIImage())
    }
    
    func testUserList_error() {
        let view = UserListView(state: .error(message: "Network connection failed"))
        assertSnapshot(of: view, as: .swiftUIImage())
    }
}
```

### アニメーション特定フレーム

```swift
func testProgressAnimation_midway() {
    let view = CircularProgressView(progress: 0.5)
    assertSnapshot(of: view, as: .swiftUIImage(), named: "50percent")
}

func testProgressAnimation_complete() {
    let view = CircularProgressView(progress: 1.0)
    assertSnapshot(of: view, as: .swiftUIImage(), named: "complete")
}
```

## CI/CD統合

### スナップショットの管理

```
MyAppTests/
├── __Snapshots__/
│   ├── ProfileViewSnapshotTests/
│   │   ├── testProfileView.1.png
│   │   ├── testProfileView_darkMode.1.png
│   │   └── testProfileView_largeText.1.png
│   └── HomeScreenSnapshotTests/
│       ├── testHomeScreen_iPhone15Pro.1.png
│       └── testHomeScreen_iPadPro12_9.1.png
```

### .gitattributes設定

```gitattributes
# スナップショット画像をLFSで管理
*/__Snapshots__/**/*.png filter=lfs diff=lfs merge=lfs -text
```

### GitHub Actions

```yaml
name: Snapshot Tests

on:
  pull_request:
    paths:
      - '**/*.swift'
      - '**/Assets.xcassets/**'

jobs:
  snapshot-test:
    runs-on: macos-14
    
    steps:
      - uses: actions/checkout@v4
        with:
          lfs: true
      
      - name: Select Xcode
        run: sudo xcode-select -s /Applications/Xcode_15.2.app
      
      - name: Run Snapshot Tests
        run: |
          xcodebuild test \
            -workspace MyApp.xcworkspace \
            -scheme MyAppTests \
            -destination 'platform=iOS Simulator,name=iPhone 15 Pro'
      
      - name: Upload Failed Snapshots
        if: failure()
        uses: actions/upload-artifact@v4
        with:
          name: failed-snapshots
          path: |
            **/Failures/**
            **/__Snapshots__/**
```

## 差分の許容

### perceptualPrecision

```swift
// わずかなアンチエイリアスの差異を許容
assertSnapshot(
    of: view,
    as: .image(perceptualPrecision: 0.98)  // 98%一致で合格
)

// より厳密なチェック
assertSnapshot(
    of: view,
    as: .image(precision: 1.0, perceptualPrecision: 1.0)
)
```

### 動的コンテンツのマスキング

```swift
extension UIView {
    func maskDynamicContent() -> UIView {
        // 日時表示などをマスク
        subviews.filter { $0.accessibilityIdentifier == "timestamp" }
            .forEach { $0.isHidden = true }
        return self
    }
}

func testFeed_maskTimestamps() {
    let view = FeedView(posts: Post.mockList)
    let controller = UIHostingController(rootView: view)
    
    // タイムスタンプをマスクしてスナップショット
    assertSnapshot(
        of: controller.view.maskDynamicContent(),
        as: .image
    )
}
```

## ベストプラクティス

### 命名規則

```swift
// ファイル名: {ViewName}SnapshotTests.swift
// テスト名: test{ViewName}_{State}_{Device}_{Theme}

func testProfileView_editing_iPhone15Pro_dark() { }
func testProfileView_viewing_iPadPro_light() { }
```

### テストの構造化

```swift
final class ProfileViewSnapshotTests: XCTestCase {
    
    // MARK: - Default State
    
    func testDefaultState() {
        assertSnapshot(of: makeView(), as: .swiftUIImage())
    }
    
    // MARK: - User Interaction States
    
    func testEditingState() {
        assertSnapshot(of: makeView(isEditing: true), as: .swiftUIImage())
    }
    
    // MARK: - Device Variations
    
    func testOnSmallDevice() {
        assertSnapshot(of: makeView(), as: .swiftUIImage(size: SnapshotDevice.iPhoneSE.size))
    }
    
    // MARK: - Accessibility
    
    func testLargeText() {
        assertSnapshot(
            of: makeView(),
            as: .swiftUIImage(traits: .init(preferredContentSizeCategory: .accessibilityLarge))
        )
    }
    
    // MARK: - Helpers
    
    private func makeView(isEditing: Bool = false) -> some View {
        ProfileView(user: .mock, isEditing: isEditing)
    }
}
```

## チェックリスト

### 導入時
- [ ] swift-snapshot-testingをSPMで追加
- [ ] スナップショットディレクトリをGit管理に含める
- [ ] .gitattributesでLFS設定（必要に応じて）

### テスト作成時
- [ ] 重要なUI状態をカバー（ローディング、エラー、空、データあり）
- [ ] ダークモード対応を確認
- [ ] 主要デバイスサイズでテスト
- [ ] アクセシビリティ設定でテスト

### メンテナンス時
- [ ] 意図的なUI変更時は `withSnapshotTesting(record: .all) { ... }` でラップして再生成
- [ ] 差分が出た場合は変更が意図的かレビュー
- [ ] CIでの失敗時はアーティファクトを確認

