Skip to content

Instantly share code, notes, and snippets.

@graffhyrum
Last active July 26, 2024 20:18
Show Gist options
  • Save graffhyrum/1cfef211eef27df6672a899776c8415d to your computer and use it in GitHub Desktop.
Save graffhyrum/1cfef211eef27df6672a899776c8415d to your computer and use it in GitHub Desktop.
Wrap some callback action in a new browser instance with setup and teardown handled
import {
BrowserContextOptions,
BrowserType,
LaunchOptions,
Page,
} from '@playwright/test';
function doWithNewBrowser(
callback: (page: Page, ...args: any[]) => Promise<any>,
browser: BrowserType,
configOptions?: {
browserOptions?: LaunchOptions;
contextOptions?: BrowserContextOptions;
},
) {
return async (...args: any[]) => {
const thisBrowser = await browser.launch(configOptions?.browserOptions);
const context = await thisBrowser.newContext(configOptions?.contextOptions);
const page = await context.newPage();
try {
return await callback(page, ...args);
} finally {
await context.close();
await thisBrowser.close();
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment