Managing Browser Lifecycle and State in Playwright

μž‘μ„±μž

μΉ΄ν…Œκ³ λ¦¬:

← ν”Όλ“œλ‘œ
DEV Community · Styrow.dev · 2026-09-06 개발(SW)

Styrow.dev

πŸ”₯ SDET Interview Scenario of the Day:
Browser lifecycle bottlenecks killing your Playwright suite?

πŸ“Œ Problem Statement
Large QA suites launch new browsers per test file. test.use({ context: true }) helps but browser process startup remains the bottleneck at scale.

πŸ’‘ Solution & Code Walkthrough
Use globalSetup to launch one browser, then spawn isolated contexts per worker. Share the browser process but never share contexts across tests.

// playwright.config.js
const { chromium } = require('playwright');

module.exports = {
  globalSetup: async () => {
    global.__browser = await chromium.launch();
  },
  globalTeardown: async () => {
    await global.__browser.close();
  },
  use: {
    context: async ({ browser }, use) => {
      const context = await browser.newContext();
      await use(context);
      await context.close();
    }
  }
};

Enter fullscreen mode Exit fullscreen mode

Isolation risks & mitigation:
❌ Shared session state / cookies / memory leaks
βœ… Fresh context per test file + context.clearCookies() + context.clearPermissions()
βœ… beforeEach resets storage state
βœ… Workers run in parallel with separate contexts

Cleanup reliability:
❌ Tests failing skip teardown
βœ… afterAll hooks + try/finally in global teardown
βœ… context.close() in afterEach even on failure
βœ… Use teardown project option for guaranteed cleanup

πŸ”‘ Key Takeaways
β€’ Share browser process, isolate contexts
β€’ Context = true gives cookie/session isolation
β€’ Global setup/teardown controls lifecycle
β€’ Always cleanup in finally blocks

❓ Quick Summary Q&A
Q: Can I share browser across workers?
A: Yes, but use separate contexts per worker.
Q: How to prevent memory leaks?
A: Close contexts after each test, monitor heap.
Q: What if test crashes?
A: Global teardown + finally blocks ensure cleanup.

TAGS: playwright, selenium, testing, automation, qa, sdets, browser-lifecycle

────────────────────────────────────────
πŸ“² 𝐅𝐑𝐄𝐄 πŒπŽππˆπ‹π„ 𝐀𝐏𝐏 β€” πŸ”πŸŽπŸŽ+ 𝐒𝐃𝐄𝐓 𝐐&𝐀𝐬
Practice real-world interview scenarios offline on the free QA Automation & SDET Prep app:

πŸ€– 𝐆𝐨𝐨𝐠π₯𝐞 𝐏π₯𝐚𝐲 (𝐀𝐧𝐝𝐫𝐨𝐒𝐝):
https://play.google.com/store/apps/details?id=com.app.seleniuminterviewquestions&referrer=utm_source%3Dlinkedin%26utm_medium%3Dsocial%26utm_campaign%3Dselenium_20260905

🍎 𝐀𝐩𝐩 π’π­π¨π«πž (π’πŽπ’):
https://apps.apple.com/app/id6786760948?pt=128640464&ct=linkedin_selenium_20260905&mt=8
────────────────────────────────────────

μ›λ¬Έμ—μ„œ 계속 β†—

μΆ”μΆœ λ³Έλ¬Έ Β· 좜처: dev.to Β· https://dev.to/styrow_dev/managing-browser-lifecycle-and-state-in-playwright-36fa