traversing-the-semantics-tree

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Traversing the Semantics Tree — When a Single Finder Won't Reach the Node

遍历语义树——当单个 Finder 无法定位节点时

The single-finder shortcuts (
onNodeWithTag
, 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
LazyColumn
snapshot caveat, and shows when traversal is the wrong tool.
单个 Finder 快捷方式(
onNodeWithTag
等)可覆盖约 95% 的测试查询。其余查询需要树导航:“这个 Text 的父节点”“这个 Row 的第三个子节点”“任何处于启用状态的兄弟节点”。本 skill 映射这些导航操作符,介绍
LazyColumn
快照注意事项,并说明何时不适合使用遍历。

When to use this skill

何时使用此 skill

  • The target node has no stable
    testTag
    and one cannot be added to production (third-party composable, dynamically generated children).
  • The test verifies structural relationships ("the second child of the row is the icon").
  • The developer chains
    .onChildren()[i].onChildAt(j)
    and wants to know whether that is the right shape.
  • The developer mentions
    onChildren
    ,
    onChild
    ,
    onParent
    ,
    onSibling
    ,
    onSiblings
    ,
    onAncestors
    ,
    filterToOne
    ,
    onFirst
    ,
    onLast
    , or
    [index]
    .
  • A
    LazyColumn
    test misses items because they are off-screen.
  • 目标节点没有稳定的
    testTag
    ,并且无法在生产代码中添加该标签(第三方 composable、动态生成的子节点)。
  • 测试需要验证结构关系(“Row 的第二个子节点是图标”)。
  • 开发者使用
    .onChildren()[i].onChildAt(j)
    链式调用,并想了解这种写法是否合适。
  • 开发者提到
    onChildren
    、
    onChild
    、
    onParent
    、
    onSibling
    、
    onSiblings
    、
    onAncestors
    、
    filterToOne
    、
    onFirst
    、
    onLast
    或
    [index]
    。
  • LazyColumn
    测试因项目位于屏幕外而遗漏元素。

When NOT to use this skill

何时不应使用此 skill

  • A
    Modifier.testTag(...)
    could be added to the target node — adding a tag is almost always cleaner than a traversal chain. See
    ../finding-nodes-by-tag-text-content/SKILL.md
    .
  • The relationship is "anywhere above" / "anywhere below" — prefer the matcher-based
    hasAnyAncestor
    /
    hasAnyDescendant
    (see
    ../composing-semantics-matchers/SKILL.md
    ).
  • The query is about a LazyColumn item by key — use
    performScrollToKey
    instead (see
    ../../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
    /
    ComposeUiTest
    . See
    ../../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
    SemanticsNodeInteraction
    (single — fails on 0 or >1) or a
    SemanticsNodeInteractionCollection
    (plural — never fails on 0).
    From a single node, go to …APIReturnsFile:line
    parent
    onParent()
    single
    Selectors.kt:36-42
    exactly one child
    onChild()
    single
    Selectors.kt:71-77
    child at an index
    onChildAt(index)
    single
    Selectors.kt:85
    all currently-composed children
    onChildren()
    collection
    Selectors.kt:53-59
    exactly one sibling
    onSibling()
    single
    Selectors.kt:119-125
    all siblings
    onSiblings()
    collection
    Selectors.kt:101-107
    every ancestor up to root
    onAncestors()
    collection
    Selectors.kt:140-146
    From a collection, narrow to …APIReturnsFile:line
    first
    onFirst()
    (=
    [0]
    )
    single
    Selectors.kt:156-158
    last
    onLast()
    single
    Selectors.kt:168-170
    nth
    [index]
    single
    SemanticsNodeInteraction.kt:261-267
    filter to a sub-collection
    filter(matcher)
    collection
    Selectors.kt:178-186
    filter to exactly one
    filterToOne(matcher)
    single
    Selectors.kt:198-206
  • 2. Do not look for
    onAncestor
    (singular) — it does not exist.
    The API surface ships only
    onAncestors()
    plural (
    Selectors.kt:140-146
    ). It returns
    [parent, grandparent, …, root]
    in that order. To assert "the immediate parent satisfies X", use
    onParent().assert(matcherX)
    or the
    hasParent(matcherX)
    predicate.
  • 3. Remember the
    useUnmergedTree
    flag is sticky.
    Every navigator carries the same
    useUnmergedTree
    value as the source
    SemanticsNodeInteraction
    (
    SemanticsNodeInteraction.kt:42-49
    ; each
    Selectors.kt
    constructor passes
    useUnmergedTree
    through unchanged). A finder created with
    onNodeWithTag(tag, useUnmergedTree = true)
    keeps the flag on across
    onChild
    /
    onParent
    /
    filter
    . Skydoves hot take #2: default merged, flip to unmerged only when targeting composition detail.
  • 4.
    onChildren()
    is a snapshot at invocation time.
    It returns nodes "currently present in the semantic tree" (
    Selectors.kt:46-52
    ). For a
    LazyColumn
    or
    LazyRow
    only the on-screen items appear. To reach an off-screen item, scroll first with
    performScrollToIndex
    /
    performScrollToKey
    /
    performScrollToNode
    (see
    ../../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 a
    [2].onChildAt(0)
    chain. Add the tag in production. Skydoves hot take #1.
  • 6. Use
    filterToOne(matcher)
    when the count assertion is implicit.
    filterToOne
    throws on 0 or >1 matches at fetch time, the same way
    onNode(matcher)
    does (
    Selectors.kt:198-206
    ). It is the collection-narrowing analogue of
    onNode(matcher)
    .
  • 1. 根据关系类型选择导航器。 每个操作符返回
    SemanticsNodeInteraction
    (单数——找到 0 个或超过 1 个节点时失败)或
    SemanticsNodeInteractionCollection
    (复数——找到 0 个节点时也不会失败)。
    从单个节点导航到……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. 不要查找
    onAncestor
    (单数)——它并不存在。
    API 仅提供复数形式
    onAncestors()
    (
    Selectors.kt:140-146
    )。它按顺序返回
    [parent, grandparent, …, root]
    。要断言“直接父节点满足 X”,请使用
    onParent().assert(matcherX)
    或
    hasParent(matcherX)
    谓词。
  • 3. 记住
    useUnmergedTree
    标志具有粘性。
    每个导航器都继承源
    SemanticsNodeInteraction
    的相同
    useUnmergedTree
    值(
    SemanticsNodeInteraction.kt:42-49
    ;每个
    Selectors.kt
    构造函数都会原样传递
    useUnmergedTree
    )。通过
    onNodeWithTag(tag, useUnmergedTree = true)
    创建的 finder 会在
    onChild
    /
    onParent
    /
    filter
    导航过程中保持该标志。Skydoves 热议观点 #2:默认使用合并树,仅在定位组合细节时切换为未合并树。
  • 4.
    onChildren()
    是调用时的快照。
    它返回“当前存在于语义树中”的节点(
    Selectors.kt:46-52
    )。对于
    LazyColumn
    或
    LazyRow
    ,只有屏幕上的项目会出现在结果中。要访问屏幕外的项目,请先使用
    performScrollToIndex
    /
    performScrollToKey
    /
    performScrollToNode
    滚动(参见
    ../../actions/clicking-and-scrolling/SKILL.md
    )。
  • 5. 按 tag 重新查找通常优于遍历。 如果树结构可能因 Compose 版本变化、文本翻译或屏幕旋转而改变,那么在目标节点上使用稳定 tag 比
    [2].onChildAt(0)
    链更持久可靠。请在生产代码中添加该标签。Skydoves 热议观点 #1。
  • 6. 当数量断言隐含在契约中时,使用
    filterToOne(matcher)
    。
    filterToOne
    会在获取节点时对 0 个或超过 1 个匹配项抛出异常,其行为与
    onNode(matcher)
    相同(
    Selectors.kt:198-206
    )。它是集合收窄场景下与
    onNode(matcher)
    对应的方法。

Patterns

模式

Pattern: prefer a tag over a deep
[index]
chain

模式:优先使用 tag,而不是深层
[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)
is exactly
onChildren()[index]
(
Selectors.kt:85
). Both fail if the index is out of range or if the resolved node count is not exactly 1 at the leaf.
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:85
)。如果索引超出范围,或者叶节点处解析出的节点数量不恰好为 1,两者都会失败。

Pattern:
filterToOne
instead of
[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
useUnmergedTree = true
set on the inner
Text
finder propagates to
onParent()
automatically — no need to repeat it.
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()
}
在内部
Text
finder 上设置的
useUnmergedTree = true
会自动传播到
onParent()
——无需重复设置。

Pattern:
onAncestors()
for the chain to root

模式:使用
onAncestors()
获取通向根节点的链

kotlin
@Test
fun confirmButton_isInsideDialog() {
    rule.setContent { ConfirmDialog() }

    rule.onNodeWithTag(ConfirmButtonTag)
        .onAncestors()
        .filterToOne(isDialog())
        .assertExists()
}
PREFERRED:
rule.onNode(hasTestTag(ConfirmButtonTag) and hasAnyAncestor(isDialog())).assertExists()
— same intent in one matcher. See
../composing-semantics-matchers/SKILL.md
.
kotlin
@Test
fun confirmButton_isInsideDialog() {
    rule.setContent { ConfirmDialog() }

    rule.onNodeWithTag(ConfirmButtonTag)
        .onAncestors()
        .filterToOne(isDialog())
        .assertExists()
}
首选:
rule.onNode(hasTestTag(ConfirmButtonTag) and hasAnyAncestor(isDialog())).assertExists()
——通过单个 matcher 表达相同意图。参见
../composing-semantics-matchers/SKILL.md
。

Pattern: 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
../../patterns/testing-lazy-lists/SKILL.md
for the full LazyColumn workflow.
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()
完整的 LazyColumn 工作流参见
../../patterns/testing-lazy-lists/SKILL.md
。

Pattern:
onSibling()
to assert "the row's other half"

模式:使用
onSibling()
断言“Row 的另一半”

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()
requires exactly one sibling (
Selectors.kt:114-125
). For multiple siblings use
onSiblings()
plus
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-125
)。如果存在多个兄弟节点,请使用
onSiblings()
配合
filterToOne(...)
。

Mandatory rules

强制规则

  • MUST prefer adding a
    Modifier.testTag(...)
    to the target node over a multi-step traversal chain. Skydoves hot take #1.
  • MUST use
    filterToOne(matcher)
    over
    filter(matcher).onFirst()
    when the contract is "exactly one match"; the former throws on >1, the latter silently picks the first.
  • MUST NOT assume
    onChildren()
    returns the full data set for a
    LazyColumn
    /
    LazyRow
    — it returns the currently-composed snapshot only. Scroll first with
    performScrollToIndex
    /
    performScrollToKey
    .
  • MUST NOT look up a singular
    onAncestor
    — only
    onAncestors()
    plural exists. Use
    onParent()
    for the immediate parent or
    hasParent(matcher)
    /
    hasAnyAncestor(matcher)
    as predicates.
  • MUST remember the
    useUnmergedTree
    flag is sticky across
    onChild
    /
    onParent
    /
    filter
    . Skydoves hot take #2.
  • PREFERRED: for "anywhere above/below" relationships, replace traversal chains with
    hasAnyAncestor
    /
    hasAnyDescendant
    from
    ../composing-semantics-matchers/SKILL.md
    .
  • 必须优先向目标节点添加
    Modifier.testTag(...)
    ,而不是使用多步遍历链。Skydoves 热议观点 #1。
  • 必须在契约为“恰好匹配一个”时使用
    filterToOne(matcher)
    ,而不是
    filter(matcher).onFirst()
    ;前者会在匹配超过一个时抛出异常,后者则会静默选择第一个。
  • 不得假定
    onChildren()
    会返回
    LazyColumn
    /
    LazyRow
    的完整数据集——它只返回当前已组合的快照。请先使用
    performScrollToIndex
    /
    performScrollToKey
    滚动。
  • 不得查找单数形式的
    onAncestor
    ——只存在复数形式
    onAncestors()
    。对于直接父节点,请使用
    onParent()
    ;也可以将
    hasParent(matcher)
    /
    hasAnyAncestor(matcher)
    用作谓词。
  • 必须记住
    useUnmergedTree
    标志在
    onChild
    /
    onParent
    /
    filter
    导航过程中具有粘性。Skydoves 热议观点 #2。
  • 首选:对于“位于任意上方或下方”的关系,使用
    ../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
    onChildren()[i]
    chain spans a
    LazyColumn
    /
    LazyRow
    boundary without a preceding
    performScrollTo*
    .
  • No
    onAncestor
    (singular) usage — only
    onParent
    ,
    onAncestors
    , or
    hasAnyAncestor
    .
  • filterToOne
    is used wherever the contract is "exactly one match";
    filter().onFirst()
    is replaced.
  • useUnmergedTree = true
    on a chain root is intentional — there is a comment or matcher reason for it.
  • ./gradlew :app:connectedDebugAndroidTest
    or
    :app:testDebugUnitTest
    passes.
  • 每条遍历链最多只包含一个导航步骤,或者通过注释说明更深层遍历的理由,并在注释中指出缺失的 tag。
  • 没有任何
    onChildren()[i]
    链跨越
    LazyColumn
    /
    LazyRow
    边界而未先执行
    performScrollTo*
    。
  • 没有使用单数形式的
    onAncestor
    ——只使用
    onParent
    、
    onAncestors
    或
    hasAnyAncestor
    。
  • 凡契约为“恰好匹配一个”的地方都使用
    filterToOne
    ;已替换
    filter().onFirst()
    。
  • 链根节点上的
    useUnmergedTree = true
    是有意设置的——存在注释或 matcher 作为设置依据。
  • ./gradlew :app:connectedDebugAndroidTest
    或
    :app:testDebugUnitTest
    通过。

References

参考资料