Skip to content

Instantly share code, notes, and snippets.

Avatar

Jose Alcérreca JoseAlcerreca

View GitHub Profile
@JoseAlcerreca
JoseAlcerreca / customizer.sh
Created June 17, 2022 14:59
Renames a whole template and data model
View customizer.sh
#!/bin/bash
#
# Copyright (C) 2022 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
View PassingTest.kt
@Test
fun loginScreen_onContinueClick_welcomeDisplayed() {
composeTestRule.onNodeWithText("Continue¨).performClick()
composeTestRule.waitUntilDoesNotExist(hasText("Loading"))
composeTestRule.onNodeWithText("Welcome").assertExists()
}
View FailingTest.kt
@Test
fun loginScreen_onContinueClick_welcomeDisplayed() {
composeTestRule.onNodeWithText("Continue¨).performClick()
// Screen still shows "Loading"
composeTestRule.onNodeWithText("Welcome").assertExists() // FAILS!
}
View MyViewModel.kt
class MyViewModel(repository…) {
val data = flow{
...
emitAll(repository.observeData())
}
}
View ComposeScreen.kt
@Composable
fun MyScreen(val viewModel: MyViewModel = viewModel()) {
val data by viewModel.data.collectAsState("Loading")
Text(greeting)
}
View MyTest.kt
composeTestRule.waitUntilExists(hasText("Continue"))
View WaitUntilUtils.kt
// Copyright 2022 Google LLC.
// SPDX-License-Identifier: Apache-2.0
fun ComposeContentTestRule.waitUntilExists(
matcher: SemanticsMatcher,
timeoutMillis: Long = 1_000L
) {
return this.waitUntilNodeCount(matcher, 1, timeoutMillis)
}
View WaitUntilUtils.kt
// Copyright 2022 Google LLC.
// SPDX-License-Identifier: Apache-2.0
fun ComposeContentTestRule.waitUntilNodeCount(
matcher: SemanticsMatcher,
count: Int,
timeoutMillis: Long = 1_000L
) {
this.waitUntil(timeoutMillis) {
this.onAllNodes(matcher).fetchSemanticsNodes().size == count
View MyTest.kt
// Click on a button
composeTestRule.onNodeWithText("Continue").performClick()
// Wait until there's one element with a "Welcome" text
composeTestRule.waitUntil {
composeTestRule
.onAllNodesWithText("Welcome")
.fetchSemanticsNodes().size == 1
}
View MyTest.kt
composeTestRule.onNodeWithText("Continue¨) .performClick()
Thread.sleep(2000) // don't do this
composeTestRule.onNodeWithText("Welcome").assertExists()