Логотип Asserting Node State And Text

Asserting Node State And Text

Спільнота
skydoves
asserting-node-state-and-text

Використовуйте цю навичку, щоб перевіряти властивості вузла семантики Compose в UI-тесті за допомогою `assertExists`, `assertDoesNotExist`, `assertIsDisplayed`, `assertIsNotDisplayed`, `assertIsDeactivated`, `assertIsEnabled`, `assertIsOn`, `assertIsOff`, `assertIsSelected`, `assertIsFocused`, `assertTextEquals`, `assertTextContains`, `assertContentDescriptionEquals`, `assertValueEquals`, `assertRangeInfoEquals`, `assertHasClickAction`, а також універсального варіанта `assert(matcher)` і булевих функцій `isDisplayed()` / `isNotDisplayed()` для предикатів `waitUntil`. Розглянуто варіанти для колекцій: `assertCountEquals`, `assertAny`, `assertAll`. Скористайтеся цією навичкою, коли розробнику потрібно перевірити, чи перемикач увімкнений, кнопка доступна, текстовий елемент показує очікуваний рядок, вузол відображається, а не лише створений, або він запитує про різницю між `assertIsDisplayed` і `assertExists`. Якщо розробник згадує будь-який API `assert*` для `SemanticsNodeInteraction`, скористайтеся цією навичкою.

Add to TypingMind

Огляд

Видавецьskydoves
Репозиторійandroid-testing-skills
Назва навичкиasserting-node-state-and-text
Зірки
338
Форки
14
Файли в пакеті
Лише інструкції
ЛіцензіяApache-2.0
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Усе необхідне — в інструкціях

    Усе потрібне моделі міститься в інструкціях — жодних додаткових файлів для синхронізації.

  • Відкритий вихідний код

    Видавець на GitHub: skydoves. Перед установленням перегляньте вихідні файли навички.

Встановлення

Установіть навичку ШІ Asserting Node State And Text у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки на GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до розділу «Плагіни» → «Навички».
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/skydoves/android-testing-skills/tree/main/compose/assertions/asserting-node-state-and-text
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Додати навичку → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/skydoves/android-testing-skills.git /tmp/android-testing-skills
mkdir -p .claude/skills
cp -r /tmp/android-testing-skills/compose/assertions/asserting-node-state-and-text .claude/skills/asserting-node-state-and-text
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Asserting Node State And Text в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Asserting Node State And Text, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для певного постачальника, тому навичка Asserting Node State And Text не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож поки навичка не потрібна, токени на її інструкції не витрачаються.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

Asserting Node State and Text — Verify Through the Framework, Not Through fetchSemanticsNode

Once a finder resolves to a SemanticsNodeInteraction, the next step is asserting it. Compose ships a typed assertion for almost every semantic property; the generic assert(matcher) covers the rest. This skill picks the right assertion, distinguishes "exists" from "displayed", and shows when boolean predicates belong inside waitUntil.

When to use this skill

  • The developer wants to verify a Switch is on, a Checkbox is unchecked, a Button is enabled, a Text equals an expected string.
  • The developer asks about assertIsDisplayed vs assertExists (one verifies on-screen, the other verifies presence in the tree).
  • The developer needs a custom assertion via assert(matcher) for a property without a typed extension.
  • The developer wants to verify a collection: "exactly 3 items", "at least one is selected", "all are enabled".
  • A test compares node.config[...] directly instead of using a typed assertion.

When NOT to use this skill

  • The right node cannot be located — see ../../finders/finding-nodes-by-tag-text-content/SKILL.md.
  • The assertion is geometric (width, height, position) — see ./asserting-bounds-and-dimensions/SKILL.md.
  • The check needs a custom SemanticsMatcher — see ../../finders/composing-semantics-matchers/SKILL.md.
  • The state changes asynchronously and the assertion is timing-sensitive — see ../../synchronization/synchronizing-with-idle/SKILL.md.

Prerequisites

  • A working ComposeTestRule / ComposeUiTest. See ../../setup/configuring-test-dependencies/SKILL.md.
  • The node has been located through onNode* / onAllNodes* / a navigator.
  • For assertIsDisplayed semantics, the node must be composed AND placed AND at least partially on-screen post-clip (Assertions.kt:30-39).

Workflow

  • 1. Pick by question type. Map the developer's question to one assertion call. Every API listed is in commonMain/.../Assertions.kt unless noted.

    QuestionAPIFile:line
    Is it in the tree?assertExists(errorMessageOnFail)SemanticsNodeInteraction.kt:124-127
    Is it gone?assertDoesNotExist()SemanticsNodeInteraction.kt:94-110
    Is it a SubcomposeLayout retained child?assertIsDeactivated()SemanticsNodeInteraction.kt:137-148
    Is it visible to the user?assertIsDisplayed() / assertIsNotDisplayed()Assertions.kt:32-53
    Is it interactive?assertIsEnabled() / assertIsNotEnabled()Assertions.kt:60-67
    Is the toggle on?assertIsOn() / assertIsOff() / assertIsToggleable()Assertions.kt:74-81, 103
    Is the radio/tab selected?assertIsSelected() / assertIsNotSelected() / assertIsSelectable()Assertions.kt:88-110
    Does it have focus?assertIsFocused() / assertIsNotFocused()Assertions.kt:117-124
    Does it equal these strings?assertTextEquals(vararg, includeEditableText=true)Assertions.kt:181-185
    Does it contain this string?assertTextContains(value, substring=false, ignoreCase=false)Assertions.kt:204-208
    Content description equals these?assertContentDescriptionEquals(vararg)Assertions.kt:139-141
    Content description contains this?assertContentDescriptionContains(value, substring, ignoreCase)Assertions.kt:158-163
    StateDescription equals X?assertValueEquals(value)Assertions.kt:216-217
    ProgressBar at this position?assertRangeInfoEquals(rangeInfo)Assertions.kt:225-227
    Has a click action?assertHasClickAction() / assertHasNoClickAction()Assertions.kt:234-243
    Anything elseassert(matcher, messagePrefixOnError = null)Assertions.kt:254-267
  • 2. assertIsDisplayed vs assertExists — pick deliberately. A node assertExists() if it is in the semantics tree (composed). A node assertIsDisplayed() if it is composed AND placed AND at least partially visible after clipping (Assertions.kt:30-39). For LazyColumn items not yet scrolled into view, assertExists() may fail (item not composed) or succeed (item composed but off-screen — depends on prefetch); assertIsDisplayed() is the right gate for "the user sees this".

  • 3. Use the typed assertion, not fetchSemanticsNode().config[...]. Typed assertions delegate to the matcher library and produce framework-formatted errors that name the failed property and dump the node (Assertions.kt:254-267 — the generic assert builds buildGeneralErrorMessage(errorMessageOnFail, selector, node)). Direct config reads bypass that error reporting and miss the auto-attached node dump.

  • 4. For collections, use the collection-typed assertions. assertCountEquals(expectedSize) for cardinality (Assertions.kt:276-292), assertAny(matcher) for "at least one matches" (fails on empty — Assertions.kt:300-312), assertAll(matcher) for "every node matches" (passes on empty — Assertions.kt:323-339).

  • 5. For waitUntil predicates, use boolean APIs, not throwing assertions. isDisplayed() returns Boolean (Assertions.kt:351) — perfect for rule.waitUntil { node.isDisplayed() }. isNotDisplayed() is its inverse (Assertions.kt:361). Both throw if multiple nodes match the finder, but never on zero. Cross-reference: ../../synchronization/synchronizing-with-idle/SKILL.md.

  • 6. For one-off properties without a typed assertion, use assert(matcher). Combine with prebuilt or composed matchers from ../../finders/composing-semantics-matchers/SKILL.md. The messagePrefixOnError lambda is for adding context when this assert is a precondition for a larger operation.

Patterns

Pattern: assertIsDisplayed over assertExists for user-facing checks

kotlin
// WRONG
@Test
fun submit_isVisibleAfterError() {
    rule.setContent { CheckoutScreen(state = state) }
    rule.onNodeWithTag(SubmitTag).assertExists()
}
// WRONG because: assertExists passes for nodes that are composed but off-screen, behind a
// dialog, or measured to zero size. The test does not prove the user actually sees the button.
kotlin
// RIGHT
@Test
fun submit_isVisibleAfterError() {
    rule.setContent { CheckoutScreen(state = state) }
    rule.onNodeWithTag(SubmitTag).assertIsDisplayed()
}

Pattern: typed assertIsOn over manual config reads

kotlin
// WRONG
@Test
fun darkMode_switch_isOn() {
    rule.setContent { SettingsScreen() }
    val node = rule.onNodeWithTag(DarkModeSwitchTag).fetchSemanticsNode()
    assertEquals(ToggleableState.On, node.config[SemanticsProperties.ToggleableState])
}
// WRONG because: bypasses the framework's error reporting. Failure prints a JUnit assertEquals
// diff with no node dump, no selector description, no hint about which screen the failure
// happened on.
kotlin
// RIGHT
@Test
fun darkMode_switch_isOn() {
    rule.setContent { SettingsScreen() }
    rule.onNodeWithTag(DarkModeSwitchTag).assertIsOn()
}

assertIsOn is assert(isOn()) (Assertions.kt:74); isOn() is expectValue(SemanticsProperties.ToggleableState, ToggleableState.On) (Filters.kt:61-62). The error names the property and dumps the node automatically.

Pattern: assertTextEquals (vararg) handles merged Text + EditableText

kotlin
// production:
TextField(value = "hello", onValueChange = {}, label = { Text("Name") },
    modifier = Modifier.testTag(NameFieldTag))

// test:
rule.onNodeWithTag(NameFieldTag).assertTextEquals("Name", "hello")

assertTextEquals(vararg) matches the unordered set of SemanticsProperties.Text plus, by default, SemanticsProperties.EditableText (Assertions.kt:181-185 → Filters.kt:274-293). To exclude editable text from the comparison: assertTextEquals("Name", includeEditableText = false).

Pattern: assertCountEquals instead of onAllNodes(...).onFirst().assertExists()

kotlin
// WRONG
rule.onAllNodesWithTag(ItemTag).onFirst().assertExists()
// WRONG because: only proves there is at least one item. Drift to zero items causes
// "no node matched" instead of a count error; drift to many is silently accepted.
kotlin
// RIGHT
rule.onAllNodesWithTag(ItemTag).assertCountEquals(3)

Pattern: assert(matcher) for properties without a typed assertion

kotlin
@Test
fun row_hasPriorityOne() {
    rule.setContent { TaskList(tasks = tasks) }

    rule.onNodeWithTag(TaskRowTag)
        .assert(SemanticsMatcher.expectValue(PriorityKey, 1))
}

PriorityKey is a custom SemanticsPropertyKey<Int> set via Modifier.semantics { priority = … }. See ../../finders/composing-semantics-matchers/SKILL.md for matcher composition.

Pattern: assertAny (fails on empty) vs assertAll (passes on empty)

kotlin
// "at least one row is selected" — must have at least one row
rule.onAllNodesWithTag(RowTag).assertAny(isSelected())

// "every row is enabled" — accepts zero rows (passes vacuously)
rule.onAllNodesWithTag(RowTag).assertAll(isEnabled())

assertAny throws AssertionError("Failed to assertAny … no node matched") on an empty collection (Assertions.kt:305-307). assertAll returns successfully on an empty collection (Assertions.kt:323-339). Pick deliberately.

Pattern: isDisplayed() inside waitUntil

kotlin
// WRONG
rule.waitUntil { rule.onNodeWithTag(SnackbarTag).assertIsDisplayed(); true }
// WRONG because: assertIsDisplayed throws on the first poll where the snackbar isn't yet
// shown. waitUntil expects a boolean — predicates that throw will fail-fast.
kotlin
// RIGHT
rule.waitUntil(timeoutMillis = 2_000) {
    rule.onAllNodesWithTag(SnackbarTag).fetchSemanticsNodes().isNotEmpty() &&
        rule.onNodeWithTag(SnackbarTag).isDisplayed()
}
rule.onNodeWithTag(SnackbarTag).assertTextContains("Saved")

isDisplayed() returns false when zero nodes match and only throws on multiple matches (Assertions.kt:343-351). Cross-reference: ../../synchronization/synchronizing-with-idle/SKILL.md for waitUntil vs mainClock.advanceTimeUntil.

Pattern: assertIsDeactivated for SubcomposeLayout retained children

kotlin
// LookaheadLayout / SubcomposeLayout may retain a previously composed slot for reuse.
// To verify the slot is currently deactivated (kept, not active):
rule.onNodeWithTag(RetainedSlotTag).assertIsDeactivated()

assertIsDeactivated fetches the node without skipping deactivated ones (SemanticsNodeInteraction.kt:137-148) and checks node.layoutInfo.isDeactivated.

Mandatory rules

  • MUST use the typed assertion (assertIsOn, assertIsEnabled, assertTextEquals, …) over fetchSemanticsNode().config[...]. The framework's error message includes the selector, the node dump, and the failed clause.
  • MUST use assertIsDisplayed() when the contract is "the user sees this"; MUST use assertExists() only when the contract is "this is in the semantics tree" (e.g. checking presence in unmerged tree without on-screen requirement).
  • MUST use the boolean isDisplayed() / isNotDisplayed() inside waitUntil { … } blocks; MUST NOT call throwing assertIs* from inside waitUntil.
  • MUST use assertCountEquals for collection cardinality; MUST NOT index [0] to imply "the only one".
  • MUST NOT repeat the same assertion across chained calls when one composed matcher would do — see ../../finders/composing-semantics-matchers/SKILL.md.
  • PREFERRED: prefer tag-anchored lookups before assertions. Skydoves hot take #1.

Verification

  • No assertion reads node.config[...] directly. All property checks go through assertIs* / assertTextEquals / assert(matcher).
  • assertIsDisplayed is used for user-visible checks; assertExists only when on-screen visibility is irrelevant.
  • waitUntil { … } blocks use isDisplayed() / isNotDisplayed() / fetchSemanticsNodes().size — no throwing assertIs* calls inside.
  • assertAny / assertAll choice matches the intended empty-collection semantics.
  • ./gradlew :app:connectedDebugAndroidTest (device) or :app:testDebugUnitTest (host) passes.
  • Failure messages mention the offending semantic property by name (proof the typed assertion is in use).

References

Поширені запитання

Що робить навичка ШІ Asserting Node State And Text?

Використовуйте цю навичку, щоб перевіряти властивості вузла семантики Compose в UI-тесті за допомогою `assertExists`, `assertDoesNotExist`, `assertIsDisplayed`, `assertIsNotDisplayed`, `assertIsDeactivated`, `assertIsEnabled`, `assertIsOn`, `assertIsOff`, `assertIsSelected`, `assertIsFocused`, `assertTextEquals`, `assertTextContains`, `assertContentDescriptionEquals`, `assertValueEquals`, `assertRangeInfoEquals`, `assertHasClickAction`, а також універсального варіанта `assert(matcher)` і булевих функцій `isDisplayed()` / `isNotDisplayed()` для предикатів `waitUntil`. Розглянуто варіанти для...

Навіщо використовувати Asserting Node State And Text у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Asserting Node State And Text — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Asserting Node State And Text у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/skydoves/android-testing-skills/tree/main/compose/assertions/asserting-node-state-and-text. TypingMind прочитає файл SKILL.md і встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Asserting Node State And Text?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Asserting Node State And Text?

Зі скількома забажаєте. У TypingMind ви можете використовувати Asserting Node State And Text із будь-якою моделлю, яка підтримує навички, зокрема з GPT, Claude, Gemini, Grok, DeepSeek, Mistral чи Llama. Для цього ви використовуєте власні ключі API.

Чи безкоштовна навичка ШІ Asserting Node State And Text?

Так. На GitHub цю навичку публікує skydoves за ліцензією Apache-2.0. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це набір інструкцій для повторного використання, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти, які вона може викликати, — код, який десь виконується й повертає результат. Натомість навичка ШІ дає моделі знання й пояснює порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі
Логотип affaan-m

Content Engine

affaan-m
СпільнотаПопулярне

Створюйте контент-системи для X, LinkedIn, TikTok, YouTube, розсилок і багатоплатформних кампаній. Для дописів, тредів, сценаріїв, контент-календарів або адаптації одного матеріалу для різних платформ…

40.4K
270.2K
Файлів: 1
Відкрити
Логотип affaan-m

Crosspost

affaan-m
СпільнотаПопулярне

Поширюйте контент на X, LinkedIn, Threads і Bluesky, адаптуючи його для кожної платформи за шаблонами контент-двигуна. Ніколи не публікуйте однаковий контент на різних платформах. Коли користувач…

40.4K
270.2K
Файлів: 1
Відкрити
Логотип affaan-m

Deep Research

affaan-m
СпільнотаПопулярне

Проводьте глибокі дослідження за кількома джерелами за допомогою MCP firecrawl і exa. Шукайте в інтернеті, узагальнюйте результати й створюйте звіти з посиланнями на джерела. Для ретельного дослідження будь-якої теми…

40.4K
270.2K
Файлів: 1
Відкрити
Логотип affaan-m

Documentation Lookup

affaan-m
СпільнотаПопулярне

Використовуйте актуальну документацію бібліотек і фреймворків через Context7 MCP замість даних навчання. Для запитань про налаштування, довідки з API, прикладів коду або згаданого користувачем фреймворку (наприклад, React,…

40.4K
270.2K
Файлів: 1
Відкрити

Створіть власний робочий простір зі ШІ вже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇