Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 858
Mohammad Derakhshan Avatar asked May 28 '26 21:05

Mohammad Derakhshan


1 Answers

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

like image 61
James Jordan Taylor Avatar answered May 30 '26 10:05

James Jordan Taylor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!