Search code examples
androidandroid-jetpack-composeandroid-testingandroid-compose-textfield

Android compose test TextField input type


How would you go about testing what input type TextField uses, for example if I wanted to test if user input has an alphanumeric keyboard type or numeric.

I can see that in SemanticProperties there is ImeAction, but I can't see anything I could use to check KeyboardOptions that you set in TextField.


Solution

  • You can use something like:

        val platformTextInputService = mock<PlatformTextInputService>()
        val textInputService = TextInputService(platformTextInputService)
        composeRule.setContent {
    
            CompositionLocalProvider(
                LocalTextInputService provides textInputService
            ) {
                val text = remember { mutableStateOf("") }
                TextField(
                    modifier = Modifier.testTag(TextfieldTag),
                    value = text.value,
                    onValueChange = { text.value = it },
                    keyboardOptions = KeyboardOptions(
                        keyboardType = KeyboardType.Number
                    )
                )
            }
        }
    
    
        composeRule.onNodeWithTag(TextfieldTag).performClick()
    
        composeRule.runOnIdle {
            verify(platformTextInputService, atLeastOnce()).startInput(
                value = any(),
                imeOptions = eq(
                    ImeOptions(
                        keyboardType = KeyboardType.Number,
                    )
                ),
                onEditCommand = any(),
                onImeActionPerformed = any()
            )
        }