Unverified Commit 66408466 authored by Jan Kaifer's avatar Jan Kaifer Committed by GitHub

Document how chain works in BrowserInterface and chain to `browser.eval` (#44085)

Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent f6cba806
export type Event = 'request'
// This is the base Browser interface all browser
// classes should build off of, it is the bare
// methods we aim to support across tests
export class BrowserInterface {
/**
* This is the base Browser interface all browser
* classes should build off of, it is the bare
* methods we aim to support across tests
*
* They will always await last executed command.
* The interface is mutable - it doesn't have to be in sequece.
*
* You can manually await this interface to wait for completion of the last scheduled command.
*/
export class BrowserInterface implements PromiseLike<any> {
private promise: any
private then: any
then: PromiseLike<any>['then']
private catch: any
protected chain(nextCall: any): BrowserInterface {
......@@ -18,6 +25,24 @@ export class BrowserInterface {
return this
}
/**
* This function will run in chain - it will wait for previous commands.
* But it won't have an effect on chain value and chain will still be green if this throws.
*/
protected chainWithReturnValue<T>(
callback: (...args: any[]) => Promise<T>
): Promise<T> {
return new Promise<T>((resolve, reject) => {
this.chain(async (...args: any[]) => {
try {
resolve(await callback(...args))
} catch (error) {
reject(error)
}
})
})
}
async setup(browserName: string, locale?: string): Promise<void> {}
async close(): Promise<void> {}
async quit(): Promise<void> {}
......
......@@ -281,8 +281,8 @@ export class Playwright extends BrowserInterface {
return this.chain((el) => el.getAttribute(attr))
}
async hasElementByCssSelector(selector: string) {
return this.eval(`!!document.querySelector('${selector}')`) as any
hasElementByCssSelector(selector: string) {
return this.eval<boolean>(`!!document.querySelector('${selector}')`)
}
keydown(key: string): BrowserInterface {
......@@ -344,19 +344,19 @@ export class Playwright extends BrowserInterface {
})
}
async eval(snippet) {
// TODO: should this and evalAsync be chained? Might lead
// to bad chains
return page
.evaluate(snippet)
.catch((err) => {
console.error('eval error:', err)
return null
})
.then(async (val) => {
await page.waitForLoadState()
return val
})
eval<T = any>(snippet): Promise<T> {
return this.chainWithReturnValue(() =>
page
.evaluate(snippet)
.catch((err) => {
console.error('eval error:', err)
return null
})
.then(async (val) => {
await page.waitForLoadState()
return val as T
})
)
}
async evalAsync(snippet) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment