Communitygithub.com

ComeOnOliver/skillshub

用於編寫 UI 測試、記錄互動、處理測試競爭條件、時間相依性、不一致的通過/失敗行為或 XCTest UI 測試不穩定時使用 — 涵蓋 UI 自動化錄製(WWDC 2025)、基於條件的等待、網路條件設定、多因素測試、崩潰除錯以及無障礙優先的測試模式

skillshub 是什麼?

此技能專注於解決 Apple 平台(iOS、iPadOS、macOS、watchOS、tvOS 及 visionOS)上 UI 測試的不穩定問題,核心原則是「等待條件,而非隨機逾時」。它詳細說明了如何使用 `waitForExistence`、`XCTestExpectation` 和基於謂詞的輪詢模式來取代 `sleep()`,從而消除因時間猜測引起的競爭條件。技能文件不僅涵蓋了傳統的條件式等待模式,還深入介紹了 Xcode 26 中全新的「錄製 UI 自動化」功能,包括如何錄製互動、跨裝置與語言重播,以及透過影片回放除錯失敗案例。此外,它也提供了無障礙優先的測試策略(如使用 `accessibilityIdentifier` 避免本地化問題)、多因素測試(跨裝置與螢幕尺寸)、網路請求與動畫處理的配套模式,以及完整的測試檢查清單與常見錯誤範例。無論是開發者還是 AI 代理使用者,都能透過此技能快速產出穩定、可維護且跨平台一致的 UI 測試程式碼。

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

在你喜歡的 AI 中提問

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

說明文件

UI 測試

概述

等待條件,而非任意的逾時。核心原則:不穩定的測試源自於猜測操作需要多久時間。基於條件的等待能消除競爭條件。

WWDC 2025 新功能:錄製 UI 自動化讓您可以錄製互動、跨裝置/語言重播,並檢視測試執行的影片錄影。

範例提示

以下是開發者會問的真實問題,此技能專為回答這些問題而設計:

1. 「我的 UI 測試在本機 Mac 上通過,但在 CI 上失敗。如何讓它們更可靠?」

→ 此技能展示可在不同裝置/速度下運作的基於條件等待模式,消除 CI 時間差異

2. 「我的測試用了 sleep(2) 和 sleep(5),但它們仍然不穩定。如何用真實條件取代任意的逾時?」

→ 此技能示範了 waitForExistence、XCTestExpectation 以及針對資料載入、網路請求和動畫的輪詢模式

3. 「我剛用 Xcode 26 的錄製 UI 自動化錄製了一個測試。如何檢視影片並除錯失敗?」

→ 此技能涵蓋了影片除錯工作流程,用於分析錄影並找出測試失敗的確切步驟

4. 「我的測試在 iPad 上失敗,但在 iPhone 上通過。如何撰寫能在所有裝置尺寸上運作的測試?」

→ 此技能解釋了多因素測試策略和裝置獨立的謂詞,以實現穩健的跨裝置測試

5. 「我想撰寫不穩定的測試。我需要知道哪些關鍵模式?」

→ 此技能提供了基於條件等待的範本、無障礙優先模式,以及可靠測試架構的決策樹


紅旗 — 測試可靠性問題

如果您看到任何這些情況,請懷疑時間問題:

  • 測試在本機通過,在 CI 失敗(時間差異)
  • 測試有時通過,有時失敗(競爭條件)
  • 測試使用 sleep() 或 Thread.sleep()(任意延遲)
  • 測試失敗並顯示「找不到 UI 元素」,然後重試通過
  • 測試執行時間過長(等待最壞情況)

快速決策樹

測試失敗?
├─ 找不到元素?
│  └─ 使用 waitForExistence(timeout:) 而非 sleep()
├─ 本機通過,CI 失敗?
│  └─ 用條件輪詢取代 sleep()
├─ 動畫造成問題?
│  └─ 等待動畫完成,不要停用
└─ 網路請求時間問題?
   └─ 使用 XCTestExpectation 或 waitForExistence

核心模式:基於條件的等待

❌ 錯誤(任意逾時):

func testButtonAppears() {
    app.buttons["Login"].tap()
    sleep(2)  // ❌ 猜測它需要 2 秒
    XCTAssertTrue(app.buttons["Dashboard"].exists)
}

✅ 正確(等待條件):

func testButtonAppears() {
    app.buttons["Login"].tap()
    let dashboard = app.buttons["Dashboard"]
    XCTAssertTrue(dashboard.waitForExistence(timeout: 5))
}

常見 UI 測試模式

模式 1:等待元素出現

// 等待元素出現
func waitForElement(_ element: XCUIElement, timeout: TimeInterval = 5) -> Bool {
    return element.waitForExistence(timeout: timeout)
}

// 使用
XCTAssertTrue(waitForElement(app.buttons["Submit"]))

模式 2:等待元素消失

func waitForElementToDisappear(_ element: XCUIElement, timeout: TimeInterval = 5) -> Bool {
    let predicate = NSPredicate(format: "exists == false")
    let expectation = XCTNSPredicateExpectation(predicate: predicate, object: element)
    let result = XCTWaiter().wait(for: [expectation], timeout: timeout)
    return result == .completed
}

// 使用
XCTAssertTrue(waitForElementToDisappear(app.activityIndicators["Loading"]))

模式 3:等待特定狀態

func waitForButton(_ button: XCUIElement, toBeEnabled enabled: Bool, timeout: TimeInterval = 5) -> Bool {
    let predicate = NSPredicate(format: "isEnabled == %@", NSNumber(value: enabled))
    let expectation = XCTNSPredicateExpectation(predicate: predicate, object: button)
    let result = XCTWaiter().wait(for: [expectation], timeout: timeout)
    return result == .completed
}

// 使用
let submitButton = app.buttons["Submit"]
XCTAssertTrue(waitForButton(submitButton, toBeEnabled: true))
submitButton.tap()

模式 4:無障礙識別碼

在 App 中設定:

Button("Submit") {
    // 動作
}
.accessibilityIdentifier("submitButton")

在測試中使用:

func testSubmitButton() {
    let submitButton = app.buttons["submitButton"]  // 使用識別碼,而非標籤
    XCTAssertTrue(submitButton.waitForExistence(timeout: 5))
    submitButton.tap()
}

原因:無障礙識別碼不會隨本地化而改變,在 UI 更新時保持穩定。

模式 5:網路請求延遲

func testDataLoads() {
    app.buttons["Refresh"].tap()

    // 等待載入指示器消失
    let loadingIndicator = app.activityIndicators["Loading"]
    XCTAssertTrue(waitForElementToDisappear(loadingIndicator, timeout: 10))

    // 現在驗證資料已載入
    XCTAssertTrue(app.cells.count > 0)
}

模式 6:動畫處理

func testAnimatedTransition() {
    app.buttons["Next"].tap()

    // 等待目標視圖出現
    let destinationView = app.otherElements["DestinationView"]
    XCTAssertTrue(destinationView.waitForExistence(timeout: 2))

    // 可選:再等一點時間讓動畫穩定
    // 僅在絕對必要時使用
    RunLoop.current.run(until: Date(timeIntervalSinceNow: 0.3))
}

測試檢查清單

撰寫測試前

  • 為所有互動元素使用無障礙識別碼
  • 避免硬編碼標籤(改用識別碼)
  • 規劃網路延遲和動畫
  • 選擇合適的逾時時間(UI 2 秒,網路 10 秒)

撰寫測試時

  • 使用 waitForExistence() 而非 sleep()
  • 針對複雜條件使用謂詞
  • 測試成功和失敗路徑
  • 讓測試獨立(可以按任何順序執行)

撰寫測試後

  • 在本機執行測試 10 次(捕捉不穩定)
  • 在支援的最慢裝置上執行測試
  • 在 CI 環境中執行測試
  • 檢查測試持續時間(如果每個測試 >30 秒,則進行最佳化)

Xcode UI 測試技巧

用於測試的啟動參數

func testExample() {
    let app = XCUIApplication()
    app.launchArguments = ["UI-Testing"]
    app.launch()
}

在 App 程式碼中:

if ProcessInfo.processInfo.arguments.contains("UI-Testing") {
    // 使用模擬資料、跳過入門流程等
}

更快的測試執行

override func setUpWithError() throws {
    continueAfterFailure = false  // 第一次失敗時停止
}

除錯失敗測試

func testExample() {
    // 失敗時截圖
    addUIInterruptionMonitor(withDescription: "Alert") { alert in
        alert.buttons["OK"].tap()
        return true
    }

    // 列印元素層級
    print(app.debugDescription)
}

常見錯誤

❌ 對所有事情使用 sleep()

sleep(5)  // ❌ 如果操作在 1 秒內完成,會浪費時間

❌ 未處理動畫

app.buttons["Next"].tap()
XCTAssertTrue(app.buttons["Back"].exists)  // ❌ 可能在動畫期間失敗

❌ 硬編碼文字標籤

app.buttons["Submit"].tap()  // ❌ 本地化後會中斷

❌ 測試彼此相依

// ❌ 測試 2 假設測試 1 先執行
func test1_Login() { /* ... */ }
func test2_ViewDashboard() { /* 假設已登入 */ }

❌ 沒有逾時策略

element.waitForExistence(timeout: 100)  // ❌ 太長
element.waitForExistence(timeout: 0.1)  // ❌ 太短

使用合適的逾時時間:

  • UI 動畫:2-3 秒
  • 網路請求:10 秒
  • 複雜操作:最多 30 秒

實際影響

改善前(使用 sleep()):

  • 測試套件:15 分鐘(等待最壞情況)
  • 不穩定測試:20% 失敗率
  • CI 失敗:50% 需要重試

改善後(基於條件的等待):

  • 測試套件:5 分鐘(僅在需要時等待)
  • 不穩定測試:<2% 失敗率
  • CI 失敗:<5% 需要重試

關鍵見解:當等待實際條件而非猜測時間時,測試完成得更快且更可靠。


錄製 UI 自動化

概述

Xcode 26 新功能:使用影片錄製記錄、重播和檢視 UI 自動化測試。

三個階段:

  1. 錄製 — 將互動(點按、滑動、硬體按鈕按下)捕捉為 Swift 程式碼
  2. 重播 — 在多個裝置、語言、區域、方向中執行
  3. 檢視 — 觀看影片錄製、分析失敗、檢視 UI 元素覆蓋層

支援的平台:iOS、iPadOS、macOS、watchOS、tvOS、axiom-visionOS(專為 iPad 設計)

UI 自動化如何運作

關鍵原則:

  • UI 自動化像真人一樣與您的 App 互動,使用手勢和硬體事件
  • 完全獨立於您的 App 執行(無法直接存取 App 的模型/資料)
  • 使用無障礙框架作為底層技術
  • 告訴作業系統執行哪些手勢,然後同步地等待每個手勢完成

包含的動作:

  • 啟動您的 App
  • 與按鈕和導覽互動
  • 設定系統狀態(深色模式、axiom-localization 等)
  • 設定模擬位置

無障礙是基礎

關鍵理解:無障礙功能直接提供資訊給 UI 自動化。

無障礙功能看到的內容:

  • 元素類型(按鈕、文字、圖片等)
  • 標籤(可見文字)
  • 值(核取方塊等的當前狀態)
  • 框架(元素位置)
  • 識別碼(無障礙識別碼 — 不會本地化)

最佳實踐:良好的無障礙體驗 = 良好的 UI 自動化體驗。

準備您的 App 進行錄製

步驟 1:新增無障礙識別碼

SwiftUI:

Button("Submit") {
    // 動作
}
.accessibilityIdentifier("submitButton")

// 讓識別碼特定於實例
List(landmarks) { landmark in
    LandmarkRow(landmark)
        .accessibilityIdentifier("landmark-\(landmark.id)")
}

UIKit:

let button = UIButton()
button.accessibilityIdentifier = "submitButton"

// 為表格儲存格使用索引
cell.accessibilityIdentifier = "cell-\(indexPath.row)"

良好的識別碼應該是:

  • ✅ 在整個 App 中唯一
  • ✅ 描述元素內容
  • ✅ 靜態(不對內容變化做出反應)
  • ✅ 不本地化(跨語言相同)

為什麼識別碼很重要:

  • 標題/描述可能會改變,識別碼保持穩定
  • 跨本地化字串運作
  • 唯一標識具有動態內容的元素

專業提示:使用 Xcode 編碼助手新增識別碼:

提示:「為此視圖的相關部分新增無障礙識別碼」

步驟 2:使用無障礙檢查器審查無障礙設定

啟動無障礙檢查器:

  • Xcode 選單 → 開啟開發者工具 → 無障礙檢查器
  • 或:從 Spotlight 啟動

功能:

  1. 元素檢查器 — 列出任何檢視的無障礙值
  2. 屬性詳細資訊 — 按一下屬性名稱取得文件
  3. 平台支援 — 適用於所有 Apple 平台

要檢查的內容:

  • 元素有標籤
  • 互動元素有類型(按鈕,而非僅文字)
  • 為有狀態的元素設定值(核取方塊、切換開關)
  • 為具有動態/本地化內容的元素設定識別碼

範例程式碼參考:提供出色的無障礙體驗

步驟 3:新增 UI 測試目標

  1. 在 Xcode 中開啟專案設定
  2. 在目標列表下方按一下「+」
  3. 選擇 UI Testing Bundle
  4. 按一下「完成」

結果:專案中新增了包含範本測試的 UI 測試資料夾。

錄製互動

開始錄製(Xcode 26)

  1. 開啟 UI 測試原始碼檔案
  2. 彈出視窗會出現解釋如何開始錄製(僅第一次)
  3. 按一下編輯器邊距中的**「開始錄製」**按鈕
  4. Xcode 會建置並在模擬器/裝置上啟動 App

錄製期間:

  • 正常與 App 互動(點按、滑動、文字輸入等)
  • 代表互動的程式碼會即時出現在原始碼編輯器中
  • 錄製會在您輸入時更新(例如文字欄位輸入)

停止錄製:

  • 按一下 Xcode 中的**「停止執行」**按鈕

範例錄製會話

func testCreateAustralianCollection() {
    let app = XCUIApplication()
    app.launch()

    // 點按「Collections」標籤(自動錄製)
    app.tabBars.buttons["Collections"].tap()

    // 點按「+」以新增集合
    app.navigationBars.buttons["Add"].tap()

    // 點按「Edit」按鈕
    app.buttons["Edit"].tap()

    // 輸入集合名稱
    app.textFields.firstMatch.tap()
    app.textFields.firstMatch.typeText("Max's Australian Adventure")

    // 點按「Edit Landmarks」
    app.buttons["Edit Landmarks"].tap()

    // 新增地標
    app.tables.cells.containing(.staticText, identifier:"Great Barrier Reef").buttons["Add"].tap()
    app.tables.cells.containing(.staticText, identifier:"Uluru").buttons["Add"].tap()

    // 點按核取標記以儲存
    app.navigationBars.buttons["Done"].tap()
}

審查錄製的程式碼

錄製完成後,審查並調整查詢:

多個選項:每一行都有下拉選單,顯示定址元素的其他方式。

選擇建議:

  1. 對於本地化字串(文字、按鈕標籤):如果可用,選擇無障礙識別碼
  2. 對於深度巢狀檢視:選擇最短的查詢(在 App 變更時保持彈性)
  3. 對於動態內容(時間戳記、溫度):使用通用查詢或識別碼

範例:

// 文字欄位的錄製選項:
app.textFields["Collection Name"]              // ❌ 如果標籤本地化會中斷
app.textFields["collectionNameField"]          // ✅ 使用識別碼
app.textFields.element(boundBy: 0)             // ✅ 基於位置
app.textFields.firstMatch                      // ✅ 通用、最短

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

相關技能