Skip to content

Instantly share code, notes, and snippets.

@Xotabu4
Last active February 4, 2022 01:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Xotabu4/d373521767861e616feda5934d55e566 to your computer and use it in GitHub Desktop.
Save Xotabu4/d373521767861e616feda5934d55e566 to your computer and use it in GitHub Desktop.
Adding waits, scroll, and retries into webdriverio clicks
/** Add custom browser and Element commands here */
export {};
declare global {
namespace WebdriverIO {
// interface Browser {
// browserCustomCommand: (arg: any) => Promise<void>
// }
// interface MultiRemoteBrowser {
// browserCustomCommand: (arg: any) => Promise<void>
// }
interface Element {
click: (arg?: ClickOptions) => Promise<void>
}
type ClickOptions = {
button?: number;
x?: number;
y?: number;
scroll?: boolean;
scrollOptions?: ScrollOptions;
waitDisplayed?: boolean;
waitOptions?: WaitOptions;
retries?: number;
};
// https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
type ScrollOptions =
| boolean
| {
behavior?: 'auto' | 'smooth';
block?: ScrollIntoViewPositionOption;
inline?: ScrollIntoViewPositionOption;
};
type ScrollIntoViewPositionOption = 'start' | 'center' | 'end' | 'nearest';
type WaitOptions = { timeout?: number; reverse?: boolean; timeoutMsg?: string; interval?: number };
}
}
browser.overwriteCommand(
'click',
async function (originalClick, options: WebdriverIO.ClickOptions = { waitOptions: {} }) {
const {
retries = 2,
scroll = true,
scrollOptions,
waitDisplayed = true,
waitOptions = {
// @ts-ignore
timeoutMsg: `Element is not visible, so cannot be clicked: ${this.selector}`,
...options.waitOptions,
},
} = options;
let attempt = 0;
let error = null;
do {
attempt += 1;
try {
if (waitDisplayed) {
// @ts-ignore
await this.waitForDisplayed(waitOptions);
}
if (scroll) {
// @ts-ignore
await this.scrollIntoView(scrollOptions);
}
originalClick({ button: options.button, x: options.x, y: options.y });
return;
} catch (err) {
error = err;
browser.pause(100);
}
} while (attempt < retries);
throw error;
},
true,
);
@Xotabu4
Copy link
Author

Xotabu4 commented Mar 18, 2021

Add d.ts typings!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment