Mohammad Derakhshan
Mohammad Derakhshan

Reputation: 1562

Testing snack bar in android testing when using jetpack compose

I'm using jetpack compose and use this code to show my Snackbar:

 LaunchedEffect(true) {
        viewModel.snackBar.collectLatest { message ->
            scaffoldState.snackbarHostState.currentSnackbarData?.dismiss()
            scaffoldState.snackbarHostState.showSnackbar(message = message)
        }
    }

Normally, when I want to access to a compose element, I use the testTag in modifier. But the Snackbar does not have any. So how can I test that my Snackbar is shown with specific text?

I tried to use:

 composeRule.onNodeWithText(SNACKBAR_MESSAGE).assertIsDisplayed()

but it can't find any node.

Upvotes: 9

Views: 1875

Answers (2)

James Jordan Taylor
James Jordan Taylor

Reputation: 1728

I had the same issue, and ultimately resorted to the following in order to get my test to pass:

composeTestRule.onNode(
    hasText(SNACKBAR_MESSAGE),
    useUnmergedTree = true
).assertIsDisplayed()

What was of critical importance was including useUnmergedTree = true

Upvotes: 5

VIGNESH
VIGNESH

Reputation: 646

We can pass the testtag in snackbar modifier and we can assert it.

Snackbar(
      modifier = Modifier
                  .padding(horizontal = 8.dp, vertical = 8.dp)
                  .testtag("Snackbar"))
         { 
            Text(text=label,modifider=Modifier.testtag("SnackBar_Text")
          }

Testing Code

onNodeWithTag("Snackbar").assertIsDisplayed
onNodeWithTag("SnackBar_Text").assertIsDisplayed //can get text from config and assert the strings too

Upvotes: 0

Related Questions