android-jetpack-composeandroid-testing

compose can not test Dialog


I have dialog in compose:

@Composable
fun testgtt() {
    val saveDialogState = remember { mutableStateOf(false) }
    Button(onClick = { saveDialogState.value = true }, modifier = Modifier.testTag(PLACE_TAG)) {
        Text(text = "helllow")
    }

    Dialog(onDismissRequest = { saveDialogState.value = false }) {
        Text(text = "helllow",modifier = Modifier.testTag(BUTTON_TAG))
    }
}

and want to test it:

    @Test
    fun das(){
        composeTestRule.setContent {
            TerTheme {
                testgtt()
            }
        }
        composeTestRule.onRoot(useUnmergedTree = true).printToLog("currentLabelExists")
        composeTestRule.onNodeWithTag(PLACE_TAG).performClick()
        composeTestRule.onNodeWithTag(BUTTON_TAG).assertIsDisplayed()
    }

but I get this error:

java.lang.AssertionError: Failed: assertExists.
Reason: Expected exactly '1' node but found '2' nodes that satisfy: (isRoot)
Nodes found:
1) Node #1 at (l=0.0, t=0.0, r=206.0, b=126.0)px
Has 1 child
2) Node #78 at (l=0.0, t=0.0, r=116.0, b=49.0)px
Has 1 child

Inspite of the fact that I see the Dialog itself.


Solution

  • use navigation component:

    @Composable
    fun de(){
        val navController = rememberNavController()
        Scaffold { innerPadding ->
            NavHost(navController, "home", Modifier.padding(innerPadding)) {
                composable("home") {
                    // This content fills the area provided to the NavHost
                    val saveDialogState = remember { mutableStateOf(true) }
                    Button(onClick = {
                                     navController.navigate("detail_dialog")
                    }, modifier = Modifier.testTag(PLACE_TAG)) {
                        Text(text = "helllow")
                    }
                }
                dialog("detail_dialog") {
                    // This content will be automatically added to a Dialog() composable
                    // and appear above the HomeScreen or other composable destinations
                    
            Dialog(onDismissRequest = {navController.navigate("home")}) {
            Card(
                shape = RoundedCornerShape(10.dp),
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentHeight()
    //                    .padding(horizontal = 16.dp)
                    .padding(vertical = 8.dp),
                elevation = 8.dp
            ){
            Text(text = "helllow", modifier = Modifier.testTag(BUTTON_TAG))
            }
        }
                }
            }
        }
    }