Hello, I am trying to write screenshot tests for `...
# compose
a
Hello, I am trying to write screenshot tests for
HorizontalTrayUi()
and
TrayItemUi()
Its easy to test
TrayItemUi()
in isolation by mocking
TrayItemViewModel
and its exposed state flows, but whats the recommended way to test
HorizontalTrayUi()
as it calls
TrayItemUi()
which then tries to create a viewModel using
Hilt
Here’s the structure
Copy code
@Composable
fun HorizontalTrayUi(
	trayModel: TrayModle,
	viewModel: TrayViewModel = viewModel()
) {
	Text(...) // title of the tray
	LazyRow(..){
		item -> {
			TrayItemUi(item)
		}
	}
}
Copy code
@Composable
fun TrayItemUi(
	item: TrayItemModel,
	viewModel: TrayItemViewModel = viewModel()
) {
	......
}
@Pedro Gomez
p
Assume the screenshot testing library will take the screenshot of what's shown on the screen. No matter how many composable views you have inside. If A depends on B and you render A. Your screenshot will show A and B. If you only render B, A will be out of the screenshot scope. If you want to use test doubles you'll need to pass the view model from the HorizontalTrayUi even if it's used inside TrayItemUi. Looking at the code I think you'll have to modify HorizontalTrayUi API to receive the TrayItemViewModel instances or a factory. Dependency injectors are quite handy for this. You have some examples here: https://github.com/Karumi/KataSuperHeroesCompose
🙏 1
a
Thanks, I will try using Hilt in tests for injecting TrayItemViewModel — sounds like a good idea But getting TrayItemViewModel in HorizontalTrayUi() — isn’t sounding good as Composables can be nested to any level and just for tests I cannot pull all viewmodels in root composable methods.. But thanks for the idea - going to dig into Hilt usage for Tests..
p
yeap, that's why dependency injection is so useful 🙂