Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 21 additions & 11 deletions test/lib/browsers/playwright.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,19 +37,23 @@ const defaultTimeout = process.env.NEXT_E2E_TEST_TIMEOUT
// This is due to `quit` can be called anytime outside of Playwright's lifecycle,
// which can create corrupted state by terminating the context.
// [TODO] global `quit` might need to be removed, instead should introduce per-instance teardown
const pendingTeardown: Array<() => Promise<void>> = []
const pendingTeardowns = new Set<Promise<void>>()
export async function quit() {
await Promise.all(pendingTeardown.map((fn) => fn()))
await Promise.all(pendingTeardowns)
await context?.close()
await browser?.close()
context = undefined
browser = undefined
}

async function teardown(tearDownFn: () => Promise<void>) {
pendingTeardown.push(tearDownFn)
await tearDownFn()
pendingTeardown.splice(pendingTeardown.indexOf(tearDownFn), 1)
const teardownPromise = tearDownFn()
pendingTeardowns.add(teardownPromise)
try {
await teardownPromise
} finally {
pendingTeardowns.delete(teardownPromise)
}
}

interface ElementHandleExt extends ElementHandle {
Expand Down Expand Up @@ -190,7 +194,18 @@ export class Playwright<TCurrent = undefined> {

async close(): Promise<void> {
await teardown(this.teardownTracing.bind(this))
await page?.close()
if (page && !page.isClosed()) {
await page.close()
}

// clean-up existing pages
await Promise.all(
context!.pages().map(async (oldPage) => {
if (!oldPage.isClosed()) {
await oldPage.close()
}
})
)
}

async launchBrowser(browserName: string, launchOptions: Record<string, any>) {
Expand Down Expand Up @@ -233,11 +248,6 @@ export class Playwright<TCurrent = undefined> {
) {
await this.close()

// clean-up existing pages
for (const oldPage of context!.pages()) {
await oldPage.close()
}

await this.initContextTracing(url, context!)
page = await context!.newPage()

Expand Down
Loading