Skip to content

Instantly share code, notes, and snippets.

@francescortiz
Created April 17, 2020 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save francescortiz/57bfe9b16856a4cf7bbab16f91fd9f39 to your computer and use it in GitHub Desktop.
Save francescortiz/57bfe9b16856a4cf7bbab16f91fd9f39 to your computer and use it in GitHub Desktop.
Hack to make selenium tests works in headless selenium driver.
declare interface Document {
originalCreateElement<K extends keyof HTMLElementTagNameMap>(tagName: K, options?: ElementCreationOptions): HTMLElementTagNameMap[K];
addFileInputToDom(offset: number, testId: string): void;
removeFileInputFromDom(testId: string): void;
}
{
const inputsCache: HTMLInputElement[] = [];
const patchedCreateElement = <K extends keyof HTMLElementTagNameMap>(
tagName: K,
options?: ElementCreationOptions
): HTMLElementTagNameMap[K] => {
const element: HTMLElementTagNameMap[K] = document.originalCreateElement(tagName, options);
if (tagName === "input" && element instanceof HTMLInputElement) {
inputsCache.length > 20 && inputsCache.shift();
inputsCache.push(element);
}
return element;
}
document.originalCreateElement = document.createElement;
document.createElement = patchedCreateElement;
document.addFileInputToDom = (offset: number, testId: string): void => {
let found: boolean = false;
let count: number = 0;
for (const input of inputsCache) {
console.log(input);
if (input.type === "file") {
if (count === offset) {
input.setAttribute("test-id", testId);
document.body.append(input);
found = true;
break
}
count += 1;
}
}
if (!found) {
console.error("not found!")
// throw new Error(`file input with to set test-id='${testId}' could not be added to dom. There is no input element with offset ${offset}.`)
}
}
document.removeFileInputFromDom = (testId: string): void => {
document.querySelectorAll(`[@test-id="${testId}"]`).forEach(x => x.remove())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment