Jetpack Compose Testing — Conditional Clickable Components
Objective
To write Compose UI test to verify that the subtract button is not clickable when the count is 0.
Counter app code
We have a simple counter app with 3 UI components.
- A Text to display the current count.
- An add icon to increment the count by 1 when clicked.
- A subtract icon to decrement the count by 1 when clicked.
We have a requirement that the subtract button should be disabled when the count is 0 so that the count is always either zero or positive. (non-negative)
The above code works as per the requirement.
Compose Test Code
We can observe that the above test is successful.
subtract.assertHasClickAction()
indicates that the subtract icon with clickable(enabled = false)
, still has a click action in the node.
We can see that Compose UI testing provides only 3 methods related to click action.
performClick()
— To perform the action.assertHasClickAction
— To assert that the node has a click action.assertHasNoClickAction
— To assert that the node has NO click action.
In the case of the subtract icon, we have a click action in the node but it is disabled.
Solution
We have to use enabled assertion to verify if the component is clickable or not.
These two lines combined can be used to assert a conditional clickable UI component.
Please comment with your valuable feedback. It would help me to improvise.
Kindly 👏👏👏 if this was useful.
Please follow if you would like to see more content related to Android Jetpack Compose.
LinkedIn: https://www.linkedin.com/in/abhimanyu-n/