DEV Community

Styrow.dev
Styrow.dev

Posted on Originally published at styrow.dev

Managing Browser Lifecycle and State in Playwright

🔥 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
────────────────────────────────────────

Top comments (0)