Communitygithub.com

ComeOnOliver/skillshub

用于编写UI测试、记录交互、处理测试中竞态条件、时序依赖、不一致的通过/失败行为,或XCTest UI测试不稳定时使用——涵盖录制UI自动化(WWDC 2025)、基于条件的等待、网络条件、多因素测试、崩溃调试以及以无障碍为先的测试模式。

skillshub 是什么?

该技能专注于解决UI测试中的关键痛点——测试的不稳定性,特别是由时序依赖和竞态条件导致的问题。它基于一个核心原则:等待条件而非任意超时。技能详细介绍了如何用基于条件的等待模式(如`waitForExistence`、`XCTestExpectation`和`NSPredicate`)替换脆弱的`sleep()`调用,从而消除CI与本地环境的时序差异。技能还覆盖了Xcode 26中新增的录制UI自动化功能,允许开发者录制交互、跨设备和语言回放,并通过视频录制审查失败点。此外,它提供了针对不同场景(如动画处理、网络请求延迟、多设备测试)的实用代码模板和决策树,并强调了使用`accessibilityIdentifier`构建稳定、可维护测试的重要性。该技能适用于任何使用Xcode UI测试框架的Apple平台(iOS、iPadOS、macOS等),其建议可显著降低测试失败率(从20%降至<2%)并缩短测试套件运行时间。

兼容平台~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:无障碍标识

在应用中设置:

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()
}

在应用代码中:

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 自动化像人一样与您的应用交互,使用手势和硬件事件
  • 完全独立于您的应用运行(无法直接访问应用模型/数据)
  • 使用无障碍框架作为底层技术
  • 告诉操作系统要执行哪些手势,然后同步地等待其完成,一次一个

操作包括:

  • 启动您的应用
  • 与按钮和导航交互
  • 设置系统状态(深色模式、axiom-localization 等)
  • 设置模拟位置

无障碍是基础

关键理解:无障碍直接向 UI 自动化提供信息。

无障碍看到的内容:

  • 元素类型(按钮、文本、图像等)
  • 标签(可见文本)
  • 值(复选框等的当前状态)
  • 框架(元素位置)
  • 标识(无障碍标识 – 不涉及本地化)

最佳实践:优秀的无障碍体验 = 优秀的 UI 自动化体验。

为录制准备您的应用

步骤 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)"

好的标识是:

  • ✅ 在整个应用中唯一
  • ✅ 描述元素内容
  • ✅ 静态(不随内容变化而反应)
  • ✅ 不本地化(跨语言保持一致)

为什么标识很重要:

  • 标题/描述可能会变,标识保持稳定
  • 跨本地化字符串工作
  • 唯一标识具有动态内容的元素

专业提示:使用 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. 点击编辑器边距中的 “Start Recording” 按钮
  4. Xcode 构建并在模拟器/设备上启动应用

录制期间:

  • 正常与应用交互(点击、滑动、输入文本等)
  • 代表交互的代码实时出现在源代码编辑器中
  • 录制会随着您的输入而更新(例如,文本字段输入)

停止录制:

  • 点击 Xcode 中的 “Stop Run” 按钮

示例录制会话

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. 对于深层嵌套视图:选择最短查询(随着应用变化保持弹性)
  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

相关技能