Last active
February 4, 2022 01:07
-
-
Save Xotabu4/d373521767861e616feda5934d55e566 to your computer and use it in GitHub Desktop.
Adding waits, scroll, and retries into webdriverio clicks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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 }; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add d.ts typings!