traversing-the-semantics-tree
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTraversing the Semantics Tree — When a Single Finder Won't Reach the Node
遍历语义树——当单个 Finder 无法定位节点时
The single-finder shortcuts (, etc.) cover ~95% of test queries. The remainder need tree navigation: "the parent of this Text", "the third child of this Row", "any sibling that is enabled". This skill maps those navigation operators, calls out the snapshot caveat, and shows when traversal is the wrong tool.
onNodeWithTagLazyColumn单个 Finder 快捷方式( 等)可覆盖约 95% 的测试查询。其余查询需要树导航:“这个 Text 的父节点”“这个 Row 的第三个子节点”“任何处于启用状态的兄弟节点”。本 skill 映射这些导航操作符,介绍 快照注意事项,并说明何时不适合使用遍历。
onNodeWithTagLazyColumnWhen to use this skill
何时使用此 skill
- The target node has no stable and one cannot be added to production (third-party composable, dynamically generated children).
testTag - The test verifies structural relationships ("the second child of the row is the icon").
- The developer chains and wants to know whether that is the right shape.
.onChildren()[i].onChildAt(j) - The developer mentions ,
onChildren,onChild,onParent,onSibling,onSiblings,onAncestors,filterToOne,onFirst, oronLast.[index] - A test misses items because they are off-screen.
LazyColumn
- 目标节点没有稳定的 ,并且无法在生产代码中添加该标签(第三方 composable、动态生成的子节点)。
testTag - 测试需要验证结构关系(“Row 的第二个子节点是图标”)。
- 开发者使用 链式调用,并想了解这种写法是否合适。
.onChildren()[i].onChildAt(j) - 开发者提到 、
onChildren、onChild、onParent、onSibling、onSiblings、onAncestors、filterToOne、onFirst或onLast。[index] - 测试因项目位于屏幕外而遗漏元素。
LazyColumn
When NOT to use this skill
何时不应使用此 skill
- A could be added to the target node — adding a tag is almost always cleaner than a traversal chain. See
Modifier.testTag(...).../finding-nodes-by-tag-text-content/SKILL.md - The relationship is "anywhere above" / "anywhere below" — prefer the matcher-based /
hasAnyAncestor(seehasAnyDescendant).../composing-semantics-matchers/SKILL.md - The query is about a LazyColumn item by key — use instead (see
performScrollToKey,../../actions/clicking-and-scrolling/SKILL.md).../../patterns/testing-lazy-lists/SKILL.md
- 可以向目标节点添加 ——添加标签几乎总是比遍历链更简洁。参见
Modifier.testTag(...)。../finding-nodes-by-tag-text-content/SKILL.md - 关系是“位于任意上方”或“位于任意下方”——优先使用基于 matcher 的 /
hasAnyAncestor(参见hasAnyDescendant)。../composing-semantics-matchers/SKILL.md - 查询是按 key 查找 LazyColumn 项目——应改用 (参见
performScrollToKey、../../actions/clicking-and-scrolling/SKILL.md)。../../patterns/testing-lazy-lists/SKILL.md
Prerequisites
前置条件
- A working /
ComposeTestRule. SeeComposeUiTest.../../setup/configuring-test-dependencies/SKILL.md - Familiarity with the merged vs unmerged tree distinction. See .
../finding-nodes-by-tag-text-content/SKILL.md
- 可正常工作的 /
ComposeTestRule。参见ComposeUiTest。../../setup/configuring-test-dependencies/SKILL.md - 熟悉合并树与未合并树之间的区别。参见 。
../finding-nodes-by-tag-text-content/SKILL.md
Workflow
工作流
-
1. Pick the navigator by relationship type. Each operator returns either a(single — fails on 0 or >1) or a
SemanticsNodeInteraction(plural — never fails on 0).SemanticsNodeInteractionCollectionFrom a single node, go to … API Returns File:line parent onParent()single Selectors.kt:36-42exactly one child onChild()single Selectors.kt:71-77child at an index onChildAt(index)single Selectors.kt:85all currently-composed children onChildren()collection Selectors.kt:53-59exactly one sibling onSibling()single Selectors.kt:119-125all siblings onSiblings()collection Selectors.kt:101-107every ancestor up to root onAncestors()collection Selectors.kt:140-146From a collection, narrow to … API Returns File:line first (=onFirst())[0]single Selectors.kt:156-158last onLast()single Selectors.kt:168-170nth [index]single SemanticsNodeInteraction.kt:261-267filter to a sub-collection filter(matcher)collection Selectors.kt:178-186filter to exactly one filterToOne(matcher)single Selectors.kt:198-206 -
2. Do not look for(singular) — it does not exist. The API surface ships only
onAncestorplural (onAncestors()). It returnsSelectors.kt:140-146in that order. To assert "the immediate parent satisfies X", use[parent, grandparent, …, root]or theonParent().assert(matcherX)predicate.hasParent(matcherX) -
3. Remember theflag is sticky. Every navigator carries the same
useUnmergedTreevalue as the sourceuseUnmergedTree(SemanticsNodeInteraction; eachSemanticsNodeInteraction.kt:42-49constructor passesSelectors.ktthrough unchanged). A finder created withuseUnmergedTreekeeps the flag on acrossonNodeWithTag(tag, useUnmergedTree = true)/onChild/onParent. Skydoves hot take #2: default merged, flip to unmerged only when targeting composition detail.filter -
4.is a snapshot at invocation time. It returns nodes "currently present in the semantic tree" (
onChildren()). For aSelectors.kt:46-52orLazyColumnonly the on-screen items appear. To reach an off-screen item, scroll first withLazyRow/performScrollToIndex/performScrollToKey(seeperformScrollToNode).../../actions/clicking-and-scrolling/SKILL.md -
5. Re-finding by tag usually beats navigating. If the tree shape might change between Compose versions or under translation rotation, a stable tag on the target node is more durable than achain. Add the tag in production. Skydoves hot take #1.
[2].onChildAt(0) -
6. Usewhen the count assertion is implicit.
filterToOne(matcher)throws on 0 or >1 matches at fetch time, the same wayfilterToOnedoes (onNode(matcher)). It is the collection-narrowing analogue ofSelectors.kt:198-206.onNode(matcher)
-
1. 根据关系类型选择导航器。 每个操作符返回(单数——找到 0 个或超过 1 个节点时失败)或
SemanticsNodeInteraction(复数——找到 0 个节点时也不会失败)。SemanticsNodeInteractionCollection从单个节点导航到…… API 返回值 文件:行 父节点 onParent()单数 Selectors.kt:36-42恰好一个子节点 onChild()单数 Selectors.kt:71-77指定索引处的子节点 onChildAt(index)单数 Selectors.kt:85当前已组合的所有子节点 onChildren()集合 Selectors.kt:53-59恰好一个兄弟节点 onSibling()单数 Selectors.kt:119-125所有兄弟节点 onSiblings()集合 Selectors.kt:101-107直到根节点的所有祖先节点 onAncestors()集合 Selectors.kt:140-146从集合筛选为…… API 返回值 文件:行 第一个节点 (即onFirst())[0]单数 Selectors.kt:156-158最后一个节点 onLast()单数 Selectors.kt:168-170第 n 个节点 [index]单数 SemanticsNodeInteraction.kt:261-267筛选为子集合 filter(matcher)集合 Selectors.kt:178-186筛选为恰好一个节点 filterToOne(matcher)单数 Selectors.kt:198-206 -
2. 不要查找(单数)——它并不存在。 API 仅提供复数形式
onAncestor(onAncestors())。它按顺序返回Selectors.kt:140-146。要断言“直接父节点满足 X”,请使用[parent, grandparent, …, root]或onParent().assert(matcherX)谓词。hasParent(matcherX) -
3. 记住标志具有粘性。 每个导航器都继承源
useUnmergedTree的相同SemanticsNodeInteraction值(useUnmergedTree;每个SemanticsNodeInteraction.kt:42-49构造函数都会原样传递Selectors.kt)。通过useUnmergedTree创建的 finder 会在onNodeWithTag(tag, useUnmergedTree = true)/onChild/onParent导航过程中保持该标志。Skydoves 热议观点 #2:默认使用合并树,仅在定位组合细节时切换为未合并树。filter -
4.是调用时的快照。 它返回“当前存在于语义树中”的节点(
onChildren())。对于Selectors.kt:46-52或LazyColumn,只有屏幕上的项目会出现在结果中。要访问屏幕外的项目,请先使用LazyRow/performScrollToIndex/performScrollToKey滚动(参见performScrollToNode)。../../actions/clicking-and-scrolling/SKILL.md -
5. 按 tag 重新查找通常优于遍历。 如果树结构可能因 Compose 版本变化、文本翻译或屏幕旋转而改变,那么在目标节点上使用稳定 tag 比链更持久可靠。请在生产代码中添加该标签。Skydoves 热议观点 #1。
[2].onChildAt(0) -
6. 当数量断言隐含在契约中时,使用。
filterToOne(matcher)会在获取节点时对 0 个或超过 1 个匹配项抛出异常,其行为与filterToOne相同(onNode(matcher))。它是集合收窄场景下与Selectors.kt:198-206对应的方法。onNode(matcher)
Patterns
模式
Pattern: prefer a tag over a deep [index]
chain
[index]模式:优先使用 tag,而不是深层 [index]
链
[index]kotlin
// WRONG
@Test
fun second_avatar_isVisible() {
rule.setContent { ProfileGrid(profiles = profiles) }
rule.onNodeWithTag("ProfileGrid")
.onChildren()[2]
.onChildren()[0]
.assertIsDisplayed()
}
// WRONG because: layout shuffling (a header inserted, an extra wrapper, a Spacer added)
// silently changes which node is being asserted. The test passes for the wrong reason.kotlin
// RIGHT
// production:
@Composable
fun ProfileGrid(profiles: List<Profile>) {
LazyColumn(modifier = Modifier.testTag(ProfileGridTag)) {
itemsIndexed(profiles) { index, profile ->
Row(modifier = Modifier.testTag("$AvatarTagPrefix$index")) {
Avatar(profile, modifier = Modifier.testTag("$AvatarImageTagPrefix$index"))
}
}
}
}
// test:
rule.onNodeWithTag("$AvatarImageTagPrefix${1}").assertIsDisplayed()kotlin
// WRONG
@Test
fun second_avatar_isVisible() {
rule.setContent { ProfileGrid(profiles = profiles) }
rule.onNodeWithTag("ProfileGrid")
.onChildren()[2]
.onChildren()[0]
.assertIsDisplayed()
}
// WRONG because: layout shuffling (a header inserted, an extra wrapper, a Spacer added)
// silently changes which node is being asserted. The test passes for the wrong reason.kotlin
// RIGHT
// production:
@Composable
fun ProfileGrid(profiles: List<Profile>) {
LazyColumn(modifier = Modifier.testTag(ProfileGridTag)) {
itemsIndexed(profiles) { index, profile ->
Row(modifier = Modifier.testTag("$AvatarTagPrefix$index")) {
Avatar(profile, modifier = Modifier.testTag("$AvatarImageTagPrefix$index"))
}
}
}
}
// test:
rule.onNodeWithTag("$AvatarImageTagPrefix${1}").assertIsDisplayed()Pattern: traversal when no tag is available
模式:没有可用 tag 时进行遍历
kotlin
@Test
fun row_third_child_isIcon() {
rule.setContent {
Row(modifier = Modifier.testTag("toolbar")) {
Text("Title")
Spacer(Modifier.weight(1f))
Icon(Icons.Default.Share, contentDescription = "Share")
}
}
rule.onNodeWithTag("toolbar")
.onChildren()
.assertCountEquals(3)
rule.onNodeWithTag("toolbar")
.onChildAt(2)
.assertContentDescriptionEquals("Share")
}onChildAt(index)onChildren()[index]Selectors.kt:85kotlin
@Test
fun row_third_child_isIcon() {
rule.setContent {
Row(modifier = Modifier.testTag("toolbar")) {
Text("Title")
Spacer(Modifier.weight(1f))
Icon(Icons.Default.Share, contentDescription = "Share")
}
}
rule.onNodeWithTag("toolbar")
.onChildren()
.assertCountEquals(3)
rule.onNodeWithTag("toolbar")
.onChildAt(2)
.assertContentDescriptionEquals("Share")
}onChildAt(index)onChildren()[index]Selectors.kt:85Pattern: filterToOne
instead of [i]
filterToOne[i]模式:使用 filterToOne
而不是 [i]
filterToOne[i]kotlin
// WRONG
rule.onAllNodesWithTag(RowTag).onChildren().filter(hasClickAction())[0]
.assertHasClickAction()
// WRONG because: indexing into a filtered collection silently passes when the filter returns
// many. The test asserts only "at least one is clickable", not "exactly one".kotlin
// RIGHT
rule.onAllNodesWithTag(RowTag).onChildren()
.filterToOne(hasClickAction())
.assertHasClickAction()kotlin
// WRONG
rule.onAllNodesWithTag(RowTag).onChildren().filter(hasClickAction())[0]
.assertHasClickAction()
// WRONG because: indexing into a filtered collection silently passes when the filter returns
// many. The test asserts only "at least one is clickable", not "exactly one".kotlin
// RIGHT
rule.onAllNodesWithTag(RowTag).onChildren()
.filterToOne(hasClickAction())
.assertHasClickAction()Pattern: assert the parent role from a known child
模式:从已知子节点断言父节点的角色
kotlin
@Test
fun submitText_isInsideEnabledButton() {
rule.setContent {
Button(onClick = {}, modifier = Modifier.testTag("submit"), enabled = true) {
Text("Submit", modifier = Modifier.testTag("submitLabel"))
}
}
rule.onNodeWithTag("submitLabel", useUnmergedTree = true)
.onParent() // sticky: stays unmerged
.assertIsEnabled()
.assertHasClickAction()
}The set on the inner finder propagates to automatically — no need to repeat it.
useUnmergedTree = trueTextonParent()kotlin
@Test
fun submitText_isInsideEnabledButton() {
rule.setContent {
Button(onClick = {}, modifier = Modifier.testTag("submit"), enabled = true) {
Text("Submit", modifier = Modifier.testTag("submitLabel"))
}
}
rule.onNodeWithTag("submitLabel", useUnmergedTree = true)
.onParent() // sticky: stays unmerged
.assertIsEnabled()
.assertHasClickAction()
}在内部 finder 上设置的 会自动传播到 ——无需重复设置。
TextuseUnmergedTree = trueonParent()Pattern: onAncestors()
for the chain to root
onAncestors()模式:使用 onAncestors()
获取通向根节点的链
onAncestors()kotlin
@Test
fun confirmButton_isInsideDialog() {
rule.setContent { ConfirmDialog() }
rule.onNodeWithTag(ConfirmButtonTag)
.onAncestors()
.filterToOne(isDialog())
.assertExists()
}PREFERRED: — same intent in one matcher. See .
rule.onNode(hasTestTag(ConfirmButtonTag) and hasAnyAncestor(isDialog())).assertExists()../composing-semantics-matchers/SKILL.mdkotlin
@Test
fun confirmButton_isInsideDialog() {
rule.setContent { ConfirmDialog() }
rule.onNodeWithTag(ConfirmButtonTag)
.onAncestors()
.filterToOne(isDialog())
.assertExists()
}首选:——通过单个 matcher 表达相同意图。参见 。
rule.onNode(hasTestTag(ConfirmButtonTag) and hasAnyAncestor(isDialog())).assertExists()../composing-semantics-matchers/SKILL.mdPattern: LazyColumn — only on-screen children appear
模式:LazyColumn——只有屏幕上的子节点会出现
kotlin
// WRONG
rule.onNodeWithTag(ListTag).onChildren().assertCountEquals(1000)
// WRONG because: onChildren() returns a snapshot of currently composed children. A LazyColumn
// only composes the visible viewport plus a small prefetch buffer, so the count is window-sized,
// not data-set-sized.kotlin
// RIGHT — assert the visible count, OR scroll first then assert by tag
rule.onNodeWithTag(ListTag).performScrollToIndex(999)
rule.onNodeWithTag("$ItemTagPrefix${999}").assertIsDisplayed()See for the full LazyColumn workflow.
../../patterns/testing-lazy-lists/SKILL.mdkotlin
// WRONG
rule.onNodeWithTag(ListTag).onChildren().assertCountEquals(1000)
// WRONG because: onChildren() returns a snapshot of currently composed children. A LazyColumn
// only composes the visible viewport plus a small prefetch buffer, so the count is window-sized,
// not data-set-sized.kotlin
// RIGHT — assert the visible count, OR scroll first then assert by tag
rule.onNodeWithTag(ListTag).performScrollToIndex(999)
rule.onNodeWithTag("$ItemTagPrefix${999}").assertIsDisplayed()完整的 LazyColumn 工作流参见 。
../../patterns/testing-lazy-lists/SKILL.mdPattern: onSibling()
to assert "the row's other half"
onSibling()模式:使用 onSibling()
断言“Row 的另一半”
onSibling()kotlin
@Test
fun checkbox_label_isPresent() {
rule.setContent {
Row {
Checkbox(checked = true, onCheckedChange = {},
modifier = Modifier.testTag("agreeBox"))
Text("I agree", modifier = Modifier.testTag("agreeLabel"))
}
}
rule.onNodeWithTag("agreeBox")
.onSibling()
.assertTextEquals("I agree")
}onSibling()Selectors.kt:114-125onSiblings()filterToOne(...)kotlin
@Test
fun checkbox_label_isPresent() {
rule.setContent {
Row {
Checkbox(checked = true, onCheckedChange = {},
modifier = Modifier.testTag("agreeBox"))
Text("I agree", modifier = Modifier.testTag("agreeLabel"))
}
}
rule.onNodeWithTag("agreeBox")
.onSibling()
.assertTextEquals("I agree")
}onSibling()Selectors.kt:114-125onSiblings()filterToOne(...)Mandatory rules
强制规则
- MUST prefer adding a to the target node over a multi-step traversal chain. Skydoves hot take #1.
Modifier.testTag(...) - MUST use over
filterToOne(matcher)when the contract is "exactly one match"; the former throws on >1, the latter silently picks the first.filter(matcher).onFirst() - MUST NOT assume returns the full data set for a
onChildren()/LazyColumn— it returns the currently-composed snapshot only. Scroll first withLazyRow/performScrollToIndex.performScrollToKey - MUST NOT look up a singular — only
onAncestorplural exists. UseonAncestors()for the immediate parent oronParent()/hasParent(matcher)as predicates.hasAnyAncestor(matcher) - MUST remember the flag is sticky across
useUnmergedTree/onChild/onParent. Skydoves hot take #2.filter - PREFERRED: for "anywhere above/below" relationships, replace traversal chains with /
hasAnyAncestorfromhasAnyDescendant.../composing-semantics-matchers/SKILL.md
- 必须优先向目标节点添加 ,而不是使用多步遍历链。Skydoves 热议观点 #1。
Modifier.testTag(...) - 必须在契约为“恰好匹配一个”时使用 ,而不是
filterToOne(matcher);前者会在匹配超过一个时抛出异常,后者则会静默选择第一个。filter(matcher).onFirst() - 不得假定 会返回
onChildren()/LazyColumn的完整数据集——它只返回当前已组合的快照。请先使用LazyRow/performScrollToIndex滚动。performScrollToKey - 不得查找单数形式的 ——只存在复数形式
onAncestor。对于直接父节点,请使用onAncestors();也可以将onParent()/hasParent(matcher)用作谓词。hasAnyAncestor(matcher) - 必须记住 标志在
useUnmergedTree/onChild/onParent导航过程中具有粘性。Skydoves 热议观点 #2。filter - 首选:对于“位于任意上方或下方”的关系,使用 中的
../composing-semantics-matchers/SKILL.md/hasAnyAncestor替代遍历链。hasAnyDescendant
Verification
验证
- Every traversal chain has at most one navigation step, OR the deeper chain is justified by a comment naming the missing tag.
- No chain spans a
onChildren()[i]/LazyColumnboundary without a precedingLazyRow.performScrollTo* - No (singular) usage — only
onAncestor,onParent, oronAncestors.hasAnyAncestor - is used wherever the contract is "exactly one match";
filterToOneis replaced.filter().onFirst() - on a chain root is intentional — there is a comment or matcher reason for it.
useUnmergedTree = true - or
./gradlew :app:connectedDebugAndroidTestpasses.:app:testDebugUnitTest
- 每条遍历链最多只包含一个导航步骤,或者通过注释说明更深层遍历的理由,并在注释中指出缺失的 tag。
- 没有任何 链跨越
onChildren()[i]/LazyColumn边界而未先执行LazyRow。performScrollTo* - 没有使用单数形式的 ——只使用
onAncestor、onParent或onAncestors。hasAnyAncestor - 凡契约为“恰好匹配一个”的地方都使用 ;已替换
filterToOne。filter().onFirst() - 链根节点上的 是有意设置的——存在注释或 matcher 作为设置依据。
useUnmergedTree = true - 或
./gradlew :app:connectedDebugAndroidTest通过。:app:testDebugUnitTest
References
参考资料
- Compose testing overview: https://developer.android.com/develop/ui/compose/testing
- Compose testing cheat sheet: https://developer.android.com/develop/ui/compose/testing-cheatsheet
- Semantics in Compose: https://developer.android.com/develop/ui/compose/accessibility/semantics
- —
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/Selectors.kt,onParent,onChildren,onChild,onChildAt,onSibling(s),onAncestors,onFirst,onLast,filter.filterToOne - — collection
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/SemanticsNodeInteraction.ktoperator and the sticky[index]field.useUnmergedTree - —
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/Filters.kt,hasParent,hasAnyChild,hasAnySibling,hasAnyAncestorpredicate alternatives to traversal.hasAnyDescendant
- Compose 测试概述:https://developer.android.com/develop/ui/compose/testing
- Compose 测试速查表:https://developer.android.com/develop/ui/compose/testing-cheatsheet
- Compose 中的语义:https://developer.android.com/develop/ui/compose/accessibility/semantics
- ——
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/Selectors.kt、onParent、onChildren、onChild、onChildAt、onSibling(s)、onAncestors、onFirst、onLast、filter。filterToOne - ——集合
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/SemanticsNodeInteraction.kt操作符和具有粘性的[index]字段。useUnmergedTree - ——
compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/Filters.kt、hasParent、hasAnyChild、hasAnySibling、hasAnyAncestor等可替代遍历的谓词。hasAnyDescendant