Allow listening for page requests in tests (#34204)

This commit is contained in:
JJ Kasper 2022-02-10 18:02:38 -06:00 committed by GitHub
parent 4643f3c3d7
commit abf781f637
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 1 deletions

View file

@ -1,3 +1,5 @@
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
@ -68,6 +70,8 @@ export class BrowserInterface {
deleteCookies(): BrowserInterface {
return this
}
on(event: Event, cb: (...args: any[]) => void) {}
off(event: Event, cb: (...args: any[]) => void) {}
async loadPage(url: string, { disableCache: boolean }): Promise<any> {}
async get(url: string): Promise<void> {}

View file

@ -1,4 +1,4 @@
import { BrowserInterface } from './base'
import { BrowserInterface, Event } from './base'
import fs from 'fs-extra'
import {
chromium,
@ -28,6 +28,23 @@ export async function quit() {
class Playwright extends BrowserInterface {
private activeTrace?: string
private eventCallbacks: Record<Event, Set<(...args: any[]) => void>> = {
request: new Set(),
}
on(event: Event, cb: (...args: any[]) => void) {
if (!this.eventCallbacks[event]) {
throw new Error(
`Invalid event passed to browser.on, received ${event}. Valid events are ${Object.keys(
event
)}`
)
}
this.eventCallbacks[event]?.add(cb)
}
off(event: Event, cb: (...args: any[]) => void) {
this.eventCallbacks[event]?.delete(cb)
}
async setup(browserName: string) {
if (browser) return
@ -84,6 +101,9 @@ class Playwright extends BrowserInterface {
page.on('pageerror', (error) => {
console.error('page error', error)
})
page.on('request', (req) => {
this.eventCallbacks.request.forEach((cb) => cb(req))
})
if (opts?.disableCache) {
// TODO: this doesn't seem to work (dev tools does not check the box as expected)