Skip to content

Instantly share code, notes, and snippets.

Avatar

Jose Alcérreca JoseAlcerreca

View GitHub Profile
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()
View MyRepo.kt
class MyRepo(dataSource: MyDataSource) {
suspend fun getItems() {
idlingResource.setBusy() // App is busy… test must wait.
val result = dataSource.getTasks()
idlingResource.setIdle() // App is idle, ready for next operation.
return result
}
}