My question is pretty simple. How do I perform any selections on a DatePickerDialog in Jetpack compose's UI Tests?
Jetpack Compose UI Test with Material3 DatePickerDialog
537 Views Asked by Karim Omar At
2
There are 2 best solutions below
0
On
For any Jetpack Compose widget that you're unfamiliar with you can print the node structure to logcat with the following command:
composeTestRule.onRoot().printToLog("ARBITRARY_LOG_TAG")
From that you should get something like this in logcat after running the test:
| Text = '[Tuesday, January 16, 2024]'
| Role = 'Button'
| Focused = 'false'
| Selected = 'false'
| Actions = [OnClick, RequestFocus]
| MergeDescendants = 'true'
|-Node #142 at (l=411.0, t=841.0, r=537.0, b=967.0)px
| Text = '[Today, Wednesday, January 17, 2024]'
| Role = 'Button'
| Focused = 'false'
| Selected = 'false'
| Actions = [OnClick, RequestFocus]
| MergeDescendants = 'true'
|-Node #145 at (l=537.0, t=841.0, r=663.0, b=967.0)px
| Text = '[Thursday, January 18, 2024]'
| Role = 'Button'
| Focused = 'false'
| Selected = 'false'
| Actions = [OnClick, RequestFocus]
| MergeDescendants = 'true'
|-Node #148 at (l=663.0, t=841.0, r=789.0, b=967.0)px
You can then interact with those DatePicker elements by clicking on them, i.e.
composeTestRule.onNodeWithText("Tuesday, January 16, 2024").performClick()
The M3
DatePickerDialogis built using compose unlike the M2DatePickerDialog, so in order to test it, you need to know what the nodes look like. While theDatePickerDialogis active, you'll have multiple roots, so in order to get the node tree for theDatePickerDialog, you'll want to usecomposeTestRule.onAllNodes(isRoot()).get(1).printToLog("T:")to print out your node tree and examine how theDatePickerDialogworks.The dates within the date picker can be selected using
onNodeWithText, though the actual text to match isn't just the day of the month as it appears in the dialog. Instead, you'll need to match dates written out such as'Wednesday, November 15, 2023'. This is easy enough to do usingDateTimeFormatterusing the patternEEEE, MMMM d, yyyy, but be aware that the current date is also prefixed with 'Today' (Today, Thursday, November 16, 2023)Other controls within the
DatePickerDialogalso respond toonNodeWithTextsuch as the OK/Cancel buttons, oronNodeWithContentDescription, such as navigating the months or setting a year.