'How to read a value from MenuItem in XCUITest?
I have a menu item that looks like a checkbox:
I would like to click/not-click on it depending on the current value. How do I get the current value?
My code for accessing and clicking it looks like this:
let menuBars = application.menuBars
let outlineModeMenuItem = menuBars.menuItems["outline_mode"]
outlineModeMenuItem.click()
The element structure looks like this:
Attributes: MenuItem, {{0.0, 401.0}, {220.0, 22.0}}, identifier: 'outline_mode', title: 'Outline Mode', Disabled
Element subtree:
→MenuItem, 0x11e14e410, {{0.0, 401.0}, {220.0, 22.0}}, identifier: 'outline_mode', title: 'Outline Mode', Disabled
Path to element:
→Application, 0x10f10cf00, pid: 90531, title: 'Vectornator', Disabled
↳MenuBar, 0x11e1178a0, {{0.0, 0.0}, {1440.0, 24.0}}
↳MenuBarItem, 0x11ce5bad0, {{401.0, 0.0}, {50.0, 24.0}}, title: 'View'
↳Menu, 0x11ce5bbe0, {{401.0, 24.0}, {220.0, 682.0}}
↳MenuItem, 0x11e14e410, {{0.0, 401.0}, {220.0, 22.0}}, identifier: 'outline_mode', title: 'Outline Mode', Disabled
So it doesn't have any "checkbox" item above or below it. value for it is empty :/ UI reads checkbox value from UICommand.state, but that doesn't seem to be exposed on XCUIElement.
Solution 1:[1]
outlineModeMenuItem.isEnabled is the call you're looking for. It should return true when it is checked and false when it's not.
https://developer.apple.com/documentation/xctest/xcuielementattributes documents other attribute checks you might be interested in. I've not worked with a MenuItem before so it is possible isSelected might be what you're looking for.
Solution 2:[2]
So far everything points that it is not possible.
UICommand has accessibilityValue but it seems not to have any effect and actually loses value. This answer seems to confirm that too: https://stackoverflow.com/a/60317536/217022
The only way I found was to modify the title when you know that you're running UI tests. Or expose these values in some other way unrelated to UICommand.
Solution 3:[3]
I don't know if that could be applied in your case but a hacky workaround you can use is to check the startX coordinate or the length of the MenuItem element to determine whether there is a checkmark there or not. I would not actually recommend it though because it is not very flexible and should probably be handled for all possible device widths
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mike Collins |
| Solution 2 | Paulius Liekis |
| Solution 3 | drunkencheetah |

