Issue
In Jetpack compose I have a TextField and I'm trying to write Espresso UI tests. I didn't find how I can enter text in the TextField, any ideas please?
TextField(
value = textState.value,
modifier = Modifier.fillMaxWidth(),
onValueChange = {
textState.value = it
apiServiceCall(textState.value.text)
},
keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences)
)
@get:Rule
val composeTestRule = createAndroidComposeRule<MainActivity>()
@Test
fun enterTextAndMakeServiceCall() {
ActivityScenario.launch(MainActivity::class.java)
//TODO: Enter text inside the TextField
composeTestRule.onNode(hasText(getString(R.string.result)))
}
Solution
I first set the testTag
modifier on the composable I want to test:
const val MY_TEXTFIELD_TAG = "myTextFieldTag"
TextField(
value = textState.value,
modifier = Modifier.fillMaxWidth().testTag(MY_TEXTFIELD_TAG),
onValueChange = {
textState.value = it
},
keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Sentences),
)
And then from your test you can set and check the value like this:
@Test
fun setAndCheckTheTextFieldValue() {
ActivityScenario.launch(MainActivity::class.java)
val resultText = "result"
// Sets the TextField value
composeTestRule.onNodeWithTag(MY_TEXTFIELD_TAG).performTextInput(resultText)
// Asserts the TextField has the corresponding value
composeTestRule.onNodeWithTag(MY_TEXTFIELD_TAG).assert(hasText(resultText))
}
Answered By - jeprubio
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.