Skip to content

Commit

Permalink
Allow listening for page requests in tests (#34204)
Browse files Browse the repository at this point in the history
  • Loading branch information
ijjk authored Feb 11, 2022
1 parent 4643f3c commit abf781f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
4 changes: 4 additions & 0 deletions test/lib/browsers/base.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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> {}

Expand Down
22 changes: 21 additions & 1 deletion test/lib/browsers/playwright.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BrowserInterface } from './base'
import { BrowserInterface, Event } from './base'
import fs from 'fs-extra'
import {
chromium,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit abf781f

Please sign in to comment.