-
-
Save francescortiz/57bfe9b16856a4cf7bbab16f91fd9f39 to your computer and use it in GitHub Desktop.
Hack to make selenium tests works in headless selenium driver.
This file contains 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
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