Testing snack bar in android testing when using jetpack compose

Viewed 330

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 testingTag in modifier. but the snackbar does not have any. so how can I test that my snack bars is shown with specific text?

I tried to use:

 composeRule.onNodeWithText(SNACKBAR_MESSAGE).assertIsDisplayed()

but it can't find any node.

1 Answers

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
Related