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

What are browser contexts and why are they important?

The Answer

A `BrowserContext` is a lightweight, isolated browser session β€” like a fresh incognito window. Each context has its own cookies, localStorage, sessionStorage, and cache. They are crucial for test isolation and multi-user testing.

Deep Dive Explanation

Without browser contexts, you'd need a separate browser process per test (slow/expensive). Contexts make isolation fast and cheap. Playwright Test creates a new context per test by default, guaranteeing no state leakage between tests.

example.spec.ts
// Each test gets a fresh context automatically in @playwright/test
test('isolated test', async ({ context, page }) => {
  // context is fresh - no cookies from other tests
  await context.addCookies([{ name: 'session', value: 'abc', domain: 'app.com' }]);
  await page.goto('/dashboard');
});

// Creating contexts manually for multi-user tests
const ctx1 = await browser.newContext(); // User A session
const ctx2 = await browser.newContext(); // User B session
// They share ZERO state