How to test Jetpack Compose’s ProgressIndicators
One of the tasks that Android developers have to face when migrating their View
s to Jetpack Compose is to migrate their UI tests to make them compatible with the UI hierarchy offered by the composable functions in their screens.
This is relatively easy to do, and the official guide explains the new ways to think and interact with this UI hierarchy pretty well, but there may be some things that may not be so straight-forward (or at least, I couldn’t find so much information about them). One of them was testing progress bars, or as they are called now: LinearProgressIndicator
s or CircularProgressIndicator
s.
The problem: testing progress bars in Compose
With the classic View
system, testing a ProgressBar
with Espresso is quite easy:
This works as you would expect: you get your ProgressBar
and test its progress
property against a defined value.
However, we cannot directly access the progress
of a ProgressIndicator
in a Compose test as we do in the usual View
way. So, how do we do it?
The solution: ProgressBarRangeInfo
It took me a bit (and some help from Compose’s library tests) to find out how we can test the progress set in a ProgressIndicator
: there’s a semantics class called ProgressBarRangeInfo
that provides accessibility information about the status of a progress bar, that both LinearProgressIndicator
and CircularProgressIndicator
use.
There’s also a test assertion called assertRangeInfoEquals
that we can use to assert if a UI node matches a given ProgressBarRangeInfo
. Let’s check how we can make use of them in our tests:
As you can see, the test is not difficult to understand but there are a few concepts that are interesting to know about:
ProgressIndicator
s (and other composables likeSlider
s) expose their progress information with theprogressBarRangeInfo
semantics.- A
ProgressBarRangeInfo
contains the progress set in the progress bar, the range that it covers and the steps inside the range. By defaultLinearProgressIndicator
andCircularProgressIndicator
have a range between0f
and1f
. This may not apply to other composables. - You need to assert the expected
ProgressBarRangeInfo
against the semantics of the node usingassertRangeInfoEquals
.
If you need to test an indeterminate progress bar, you have the ProgressBarRangeInfo.Indeterminate
object.
And that’s the gist of it! I hope you find this information useful when migrating old tests or writing new tests for your Compose UIs.