Skip to content

Instantly share code, notes, and snippets.

@Xotabu4
Last active February 4, 2022 01:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xotabu4/108ab56142bfd1a7bacf3e247fa5dfff to your computer and use it in GitHub Desktop.
Save Xotabu4/108ab56142bfd1a7bacf3e247fa5dfff to your computer and use it in GitHub Desktop.
Describing how add automatic waits, scrolling and retries for wdio click function
import { declareClickCommand } from './customCommands';
export const baseConfig: WebdriverIO.Config = {
bail: 0,
automationProtocol: 'webdriver',
hostname: 'localhost',
protocol: 'http',
port: 4444,
path: '/wd/hub',
baseUrl: '',
connectionRetryCount: 3,
connectionRetryTimeout: 30000,
waitforTimeout: 20000,
logLevel: 'error',
reporters: ['spec'],
services: [],
specFileRetries: 1,
before: () => {
// Define your custom commands in 'before' hook
declareClickCommand()
}
};
export const retry = (handlerFn: () => boolean, maxRetries = 2) => {
let retries = 0;
let result = false;
let error = '';
do {
try {
error = '';
result = handlerFn();
} catch (e) {
result = false;
error = e;
browser.pause(500);
}
} while (retries++ < maxRetries && !result);
if (error !== '') {
throw new Error(`${error}, retried: ${retries}`);
}
};
/**
* Override original WDIO click, with automatic wait, scrolling, and retrying logic.
* $(...).click()
* 'this' has actual type of WebdriverIO.Element
* https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters
*/
export const declareClickCommand = () => {
browser.overwriteCommand(
'click',
function (originalClick, options: WebdriverIO.ClickOptions = { waitOptions: {} }) {
const {
retries = 3,
scroll = false,
scrollOptions,
waitDisplayed = true,
waitOptions = {
timeoutMsg: `Element is not visible, so cannot be clicked: ${this.selector}`,
...options.waitOptions
}
} = options;
retry(() => {
waitDisplayed && this.waitForDisplayed(waitOptions);
scroll && this.scrollIntoView(scrollOptions);
result = originalClick();
return true;
}, retries);
},
true
);
}
// Typings declaration
declare namespace WebdriverIO {
interface Element {
click: (options?: ClickOptions) => 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 };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment