Scrolling onto Element using Appium in CodeceptJS

Sandeep Dinesh
2 min readNov 11, 2020

--

You would ask why would a post be needed when you check the API documentation for CodeceptJS Appium, apparently you have scrollTo, swipe, scrollToView, scrollPageToTop, scrollPageToBottom etc.

But as always everything comes with a catch. scrollToView only works in web context, scrollPageTo* are unimplemented for UIAutomator2 and XCUIT the most common Android and iOS drivers for Appium, swipe* and scroll* needs location and offsets (recipes for test code maintenance nightmare!)

Here’s the proposed solution. We will need the good old execute_script of Appium, and the hidden/ lesser known I.executeScript API method of CodeceptJS

Let’s Jump to the Code/ TLDR:

await I.runOnAndroid(() => {I.executeScript('mobile: scroll', { strategy: 'accessibility id', selector: '~button-logout-text' });});await I.runOnIOS(() => {I.executeScript('mobile: scroll', { direction: 'down', predicateString: 'id == "logout-button"' });});

Explanation:

I have a react-native codebase where I use a sweet but powerful library react-native-testid which smartly applies the data test-ids for my mobile elements.
In Android it will be having the value of ‘content-desc’ or accessibility id of the element, and for iOS it will take the value of ‘id’

In Android, I can set the accessibility-id on Button Text inside the Button element, but not so lucky in iOS (as you can guess from the example, the reason could be the React Native magic which converts the JS code to Platform Code and how mobile elements gets inflated from it. I am no react native expert, so I will leave at this)

The executeScript delegates the calls to the underlying driver, which in Android it is UIAutomator2 which mandates strategy and selector. By default the direction is ‘down’.
strategy can be XPATH, CSS, Accessibility ID etc. (There are lots as you are aware!)

Similarly for iOS it is the direction and predicateString.
direction — up, down, right, left..
predicateString-The iOS logical selector, but pretty slow usually. (Use with minimal joins is my personal opinion.)

That’s it. Ta-Da. Your automation code will scroll to your element until it is visible! Happy Test Automation.

--

--

Sandeep Dinesh
Sandeep Dinesh

Written by Sandeep Dinesh

Test Automation, CI/CD, DevOps & SRE

Responses (1)