Hi there, so this is a question about testing Com...
# compose
s
Hi there, so this is a question about testing Compose
Pager
. I have a
ViewModel
that wants to listen to the pager's current index, so I hoisted the
PagerState
into the
ViewModel
and observe it via
snapshotFlow
. Basically this:
Copy code
class VM {
	val pagerState = PagerState(initialPage = 0)
	private val currentIndex = snapshowFlow { pagerState.currentPage }
	// do something with currentIndex
}
This works just fine. Now I'm trying to unit test my `ViewModel`:
Copy code
fun test() = runTest {
	val vm = createVm()
	vm.pagerState.scrollTo(n) // <- blocks indefinitely
	// assert that vm does the correct thing
}
Until now I had no trouble testing Compose State classes, but it seems
PagerState
has some internal mechanism that waits for a layout to happen before
scrollTo
finishes. Since this isn't happening in my test, the function blocks indefinitely. I could handle the current-page logic entirely myself but I would end up having to synchronize with the PagerState and end up with two sources of truth. Any ideas?
j
@levima
m
It makes sense that it has that internal mechanism. scrollToPage is a suspending function that is supposed to wait for the scroll to actually happen.
I suspect you’d have to spawn another thread somewhere that’s going to alter the state somehow to indicate that the scroll has happened)
s
Since it waits for a layout, I could technically turn it into a fully-fledged Compose UI test. But that's a lot of overhead just to test the page change mechanism.
l
We do use the same mechanism in other states, like in LazyLists. But without a layout pass I'm not sure you'll be able to unblock the scrollTo call. So my best advice for now would be to convert it to a compose ui test and file a ticket so we can take a better look at this 😄