πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
Back to All Questions
Question 95 of 100
Framework
Advanced

What happens if a test closes a browser context prematurely?

The Answer

If a test closes the browser context before Playwright's cleanup runs, video and trace files won't be finalized, storage state can't be saved, and subsequent test isolation may break.

Deep Dive Explanation

Playwright Test's fixture system manages context lifecycle correctly. When you manually manage contexts, you're responsible for proper cleanup in all code paths (success and failure). The `try/finally` pattern ensures `context.close()` always runs.

example.spec.ts
// ❌ Closing context manually can cause issues
test('broken context close', async ({ browser }) => {
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto('/');
  await context.close(); // Video/trace not finalized if tracing was active!
});

// βœ… Let Playwright manage the context lifecycle (use fixtures)
test('proper way', async ({ page }) => {
  // Playwright creates and destroys the context for you
  await page.goto('/');
  // Context is closed properly after test + teardown
});

// If you must manage context manually, use try/finally
test('manual context with cleanup', async ({ browser }) => {
  const context = await browser.newContext();
  try {
    const page = await context.newPage();
    await page.goto('/');
  } finally {
    await context.close(); // Always closes, even on failure
  }
});