Communitygithub.com

ComeOnOliver/skillshub

在 Xcode 26 中設定 UI 測試錄製、增強錄製測試的穩定性,或設定測試計劃以進行多配置重播時使用。基於 WWDC 2025-344「錄製、重播和審查」。

skillshub 是什麼?

此技能提供在 Xcode 26 中使用「錄製 UI 自動化」功能的完整指南,讓開發者能透過錄製使用者的操作互動,自動產生 UI 測試程式碼。技能首先介紹一個三階段工作流程:錄製(與模擬器中的應用程式互動,Xcode 會自動產生 Swift 測試碼)、重播(使用測試計劃在多種裝置、語言和設定上執行測試)、與審查(在測試報告中觀看影片錄製並分析失敗原因)。此技能特別強調錄製程式碼的脆弱性,並教導開發者如何透過加入輔助使用識別碼、等候元素出現的 `waitForExistence` 方法與明確的斷言來增強測試穩定性。此外,它還涵蓋了使用測試計劃進行多配置重播的詳細設定,包括語言、地區、深色模式等選項的 JSON 結構範例,以及透過指令列或 Xcode 圖形化介面執行測試的方法。最後,技能也提供了常見的測試模式範本(如登入流程、導覽流程、表單驗證)與反模式警告(如直接使用未加工的錄製程式碼、硬編碼座標、跳過斷言),並涵蓋了問題排除技巧,確保開發者能在 CI 環境中也能穩定地執行自動化 UI 測試。支援 Xcode 26 及相關 WWDC 內容。

相容平台~Claude Code~Codex CLI✓Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/CharlesWiltgen/Axiom/axiom-ui-recording

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

錄製 UI 自動化 (Xcode 26+)

Xcode 26 的錄製 UI 自動化功能指南,用於透過記錄使用者操作來建立 UI 測試。

三階段工作流程

取自 WWDC 2025-344:

┌─────────────────────────────────────────────────────────────┐
│                   UI 自動化工作流程                          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  1. 錄製 ──────► 在模擬器中與 App 互動                     │
│                   Xcode 捕捉為 Swift 測試程式碼             │
│                                                             │
│  2. 重播 ──────► 在各種裝置、語言、設定上執行               │
│                   使用測試計劃進行多配置                    │
│                                                             │
│  3. 審查 ──────► 在測試報告中觀看錄製影片                   │
│                   透過截圖分析失敗原因                       │
│                                                             │
└─────────────────────────────────────────────────────────────┘

階段 1:錄製

開始錄製

  1. 在 Xcode 中開啟你的 UI 測試檔案
  2. 將游標置於測試方法內
  3. 除錯 → 錄製 UI 自動化(或使用錄製按鈕)
  4. App 會在模擬器中啟動
  5. 執行動作互動 – Xcode 會產生對應程式碼
  6. 完成後停止錄製

會錄製的內容

  • 點擊按鈕、Cell、控制項
  • 輸入文字至文字欄位
  • 滑動與滾動
  • 手勢(捏合、旋轉)
  • 硬體按鈕按下(主畫面、音量)

產生的程式碼範例

// Xcode 從你的操作產生此程式碼
func testLoginFlow() {
    let app = XCUIApplication()
    app.launch()

    // 錄製:點擊 Email 欄位,輸入 Email
    app.textFields["Email"].tap()
    app.textFields["Email"].typeText("[email protected]")

    // 錄製:點擊密碼欄位,輸入密碼
    app.secureTextFields["Password"].tap()
    app.secureTextFields["Password"].typeText("password123")

    // 錄製:點擊登入按鈕
    app.buttons["Login"].tap()
}

增強錄製的程式碼

關鍵:錄製的程式碼通常較脆弱。務必增強其穩定性。

1. 加入輔助使用識別碼

錄製的程式碼使用標籤,但會因本地化而失效:

// 錄製(脆弱 - 會因本地化而失效)
app.buttons["Login"].tap()

// 增強(穩定 - 使用識別碼)
app.buttons["loginButton"].tap()

在 App 程式碼中加入識別碼:

// SwiftUI
Button("Login") { ... }
    .accessibilityIdentifier("loginButton")

// UIKit
loginButton.accessibilityIdentifier = "loginButton"

2. 加入 waitForExistence

錄製的程式碼假設元素立即存在:

// 錄製(若 App 較慢則可能失敗)
app.buttons["Login"].tap()

// 增強(等待元素)
let loginButton = app.buttons["loginButton"]
XCTAssertTrue(loginButton.waitForExistence(timeout: 5))
loginButton.tap()

3. 加入斷言

錄製的程式碼僅執行動作,不進行驗證:

// 錄製(無驗證)
app.buttons["Login"].tap()

// 增強(含斷言)
app.buttons["loginButton"].tap()
let welcomeLabel = app.staticTexts["welcomeLabel"]
XCTAssertTrue(welcomeLabel.waitForExistence(timeout: 10),
              "登入後應顯示歡迎畫面")

4. 使用更簡潔的查詢

錄製的程式碼可能包含過於具體的查詢:

// 錄製(過於具體)
app.tables.cells.element(boundBy: 0).buttons["Action"].tap()

// 增強(更簡潔)
app.buttons["actionButton"].tap()

查詢選擇指南

取自 WWDC 2025-344:

情境問題解決方案
本地化字串"Login" 會因語言而改變使用 accessibilityIdentifier
深層巢狀檢視長查詢鏈容易中斷使用最短的可能查詢
動態內容Cell 內容會改變使用識別碼或通用查詢
多個符合項查詢回傳許多元素加入唯一識別碼

最佳做法

  1. 優先使用識別碼而非標籤
  2. 使用最短的有效查詢
  3. 避免基於索引的查詢 (element(boundBy: 0))
  4. 為動態內容加入識別碼

階段 2:使用測試計劃重播

測試計劃允許在多個設定下執行相同的測試。

建立測試計劃

  1. 檔案 → 新增 → 檔案 → 測試計劃
  2. 加入測試目標
  3. 設定組態

測試計劃結構

{
  "configurations": [
    {
      "name": "iPhone - 英文",
      "options": {
        "targetForVariableExpansion": {
          "containerPath": "container:MyApp.xcodeproj",
          "identifier": "MyApp"
        },
        "language": "en",
        "region": "US"
      }
    },
    {
      "name": "iPhone - 西班牙文",
      "options": {
        "language": "es",
        "region": "ES"
      }
    },
    {
      "name": "iPhone - 深色模式",
      "options": {
        "userInterfaceStyle": "dark"
      }
    },
    {
      "name": "iPad - 橫向",
      "options": {
        "defaultTestExecutionTimeAllowance": 120,
        "testTimeoutsEnabled": true
      }
    }
  ],
  "defaultOptions": {
    "targetForVariableExpansion": {
      "containerPath": "container:MyApp.xcodeproj",
      "identifier": "MyApp"
    }
  },
  "testTargets": [
    {
      "target": {
        "containerPath": "container:MyApp.xcodeproj",
        "identifier": "MyAppUITests",
        "name": "MyAppUITests"
      }
    }
  ],
  "version": 1
}

組態選項

選項用途
language測試本地化
region測試地區格式
userInterfaceStyle測試深色/淺色模式
targetForVariableExpansion用於組態的 App 目標
testTimeoutsEnabled啟用逾時機制
defaultTestExecutionTimeAllowance逾時秒數

使用測試計劃執行

# 命令列
xcodebuild test \
  -scheme "MyApp" \
  -testPlan "MyTestPlan" \
  -destination "platform=iOS Simulator,name=iPhone 16" \
  -resultBundlePath /tmp/results.xcresult

# 在 Xcode 中
# Product → Test Plan → 選擇你的計劃
# 然後按 Cmd+U 執行測試

階段 3:審查

測試報告功能

測試完成後:

  1. 在報告導覽器檢視測試結果
  2. 觀看每個測試的錄製影片
  3. 在失敗點查看截圖
  4. 分析動作時間軸

啟用附件

在測試計劃或 scheme 中:

"options": {
  "systemAttachmentLifetime": "keepAlways",
  "userAttachmentLifetime": "keepAlways"
}

擷取自訂截圖

func testCheckout() {
    // ... 動作 ...

    // 在特定點手動截圖
    let screenshot = app.screenshot()
    let attachment = XCTAttachment(screenshot: screenshot)
    attachment.name = "結帳確認"
    attachment.lifetime = .keepAlways
    add(attachment)
}

常見模式

登入流程範本

func testLoginWithValidCredentials() throws {
    let app = XCUIApplication()
    app.launch()

    // 導覽至登入
    let showLoginButton = app.buttons["showLoginButton"]
    XCTAssertTrue(showLoginButton.waitForExistence(timeout: 5))
    showLoginButton.tap()

    // 輸入憑證
    let emailField = app.textFields["emailTextField"]
    XCTAssertTrue(emailField.waitForExistence(timeout: 5))
    emailField.tap()
    emailField.typeText("[email protected]")

    let passwordField = app.secureTextFields["passwordTextField"]
    passwordField.tap()
    passwordField.typeText("password123")

    // 提交
    app.buttons["loginButton"].tap()

    // 驗證成功
    let welcomeScreen = app.staticTexts["welcomeLabel"]
    XCTAssertTrue(welcomeScreen.waitForExistence(timeout: 10))
}

導覽流程範本

func testNavigateToSettings() throws {
    let app = XCUIApplication()
    app.launch()

    // 開啟分頁列項目
    app.tabBars.buttons["設定"].tap()

    // 驗證導覽
    let settingsTitle = app.navigationBars["設定"]
    XCTAssertTrue(settingsTitle.waitForExistence(timeout: 5))

    // 更深層導覽
    app.tables.cells["帳號"].tap()
    XCTAssertTrue(app.navigationBars["帳號"].exists)
}

表單驗證範本

func testFormValidation() throws {
    let app = XCUIApplication()
    app.launch()

    // 提交空表單
    app.buttons["submitButton"].tap()

    // 驗證錯誤訊息出現
    let errorAlert = app.alerts["錯誤"]
    XCTAssertTrue(errorAlert.waitForExistence(timeout: 5))
    XCTAssertTrue(errorAlert.staticTexts["請填寫所有欄位"].exists)

    // 關閉警告
    errorAlert.buttons["確定"].tap()
}

疑難排解

錄製無法開始

  1. 確認你在測試方法中
  2. 檢查模擬器是否可用
  3. 確認 App 可建置與執行
  4. 嘗試重新啟動 Xcode

錄製的程式碼無法運作

  1. 在互動前加入 waitForExistence
  2. 檢查輔助使用識別碼是否已設定
  3. 將查詢簡化至最短形式
  4. 手動執行 App 以驗證流程是否正常

測試在本地通過,但在 CI 失敗

  1. 增加逾時時間 以因應 CI 機器較慢的情況
  2. 為動畫加入明確的等待
  3. 檢查模擬器設定是否相符
  4. 在測試設定中停用動畫:
    app.launchArguments = ["--disable-animations"]
    

反模式

不要在 CI 中使用未加工的錄製程式碼

// 不好 - 未加工的錄製程式碼
app.buttons["Login"].tap()
app.textFields["Email"].typeText("[email protected]")

// 好 - 為 CI 增強
let loginButton = app.buttons["loginButton"]
XCTAssertTrue(loginButton.waitForExistence(timeout: 10))
loginButton.tap()

不要硬編碼座標

// 不好 - 錄製的座標
app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()

// 好 - 使用元素查詢
app.buttons["centerButton"].tap()

不要跳過斷言

// 不好 - 僅動作
app.buttons["Login"].tap()
sleep(2)  // 希望它成功

// 好 - 驗證結果
app.buttons["loginButton"].tap()
XCTAssertTrue(app.staticTexts["歡迎"].waitForExistence(timeout: 10))

資源

WWDC:2025-344, 2024-10206, 2019-413

文件:/xcode/testing/recording-ui-tests, /xctest/xcuiapplication

技能:axiom-xctest-automation, axiom-ui-testing

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相關技能