Playwright Browser Context
This chapter introduces Playwright's test isolation mechanism and the concept of Browser Context, which is a key design ensuring stable and reliable tests.
* * *
## What is Test Isolation
Test isolation means each test case runs in a completely independent environment without affecting each other.
In Playwright, each test automatically gets its own independent Browser Context.
* * *
## What is Browser Context
Browser Context is equivalent to a brand new browser profile configuration.
Creating a Context is like opening a brand new browser window, with its own Cookie, localStorage, sessionStorage, but with extremely low overhead (millisecond level).
| Concept | Analogy | Description |
| --- | --- | --- |
| Browser (Browser Instance) | Opened a browser program | High overhead, generally created only once for the entire test run |
| Browser Context (Browser Context) | Independent profile configuration in the browser | Low overhead, one per test |
| Page (Tab) | A tab in the browser | Opens pages within the Context |
Each test's `page` and `context` are completely new, so modifications to localStorage or Cookies in one test won't impact other tests.
* * *
## What is Isolated in Context
Each Browser Context completely isolates the following:
| Isolated Item | Description |
| --- | --- |
| Cookies | Each Context has independent Cookie storage |
| localStorage | Local storage is completely isolated |
| sessionStorage | Session storage is completely isolated |
| IndexedDB | Browser database isolation |
| Cache | HTTP cache isolation |
## Example
// Test A sets a Cookie
test('Test A', async ({ page })=>{
await page.goto('https://example.com/');
// Set Cookie (only effective in current Context)
await page.context().addCookies([{
name:'tutorial_session',
value:'abc123',
domain:'example.com',
path:'/',
}]);
// Subsequent operations use this Cookie
});
// Test B receives a brand new Context, without the Cookie set by Test A
test('Test B', async ({ page })=>{
await page.goto('https://example.com/');
// context().cookies() returns empty array
const cookies = await page.context().cookies();
console.log(cookies);// []
});
* * *
## Using context fixture
Besides `page`, test functions can also access the `context` fixture for Context-level operations.
## Example
test('Use context fixture', async ({ context, page })=>{
// Set permissions at Context level
await context.grantPermissions(['geolocation']);
await context.setGeolocation({ latitude:39.9, longitude:116.4});
// Intercept network at Context level
await context.route('**/*.{png,jpg,jpeg}', route => route.abort());
// page is in the same context, inheriting the above settings
await page.goto('https://example.com/');
});
* * *
## Multiple Context Scenarios
When you need to simulate multiple independent users in the same test, you can manually create Contexts.
## Example
test('Two users operate independently', async ({ browser })=>{
// Create independent Contexts for two users
const userAContext = await browser.newContext();
const userBContext = await browser.newContext();
// Pages for two users are completely isolated
const pageA = await userAContext.newPage();
const pageB = await userBContext.newPage();
await pageA.goto('https://example.com/login');
await pageB.goto('https://example.com/login');
// User A logs in
await pageA.getByLabel('Username').fill('user_a');
await pageA.getByLabel('Password').fill('password_a');
await pageA.getByRole('button',{ name:'Login'}).click();
// User B logs in (Independent Cookie/Session, do not affect each other)
await pageB.getByLabel('Username').fill('user_b');
await pageB.getByLabel('Password').fill('password_b');
await pageB.getByRole('button',{ name:'Login'}).click();
// Cleanup
await userAContext.close();
await userBContext.close();
});
* * *
## Benefits of Test Isolation
### 1. Reproducibility
Each test starts from the same initial state, with consistent results regardless of execution order.
### 2. Preventing Cascading Failures
Test A failing won't cause Test B to fail; each test is independently debuggable.
### 3. Supporting Parallel Execution
Because tests are completely independent, Playwright can safely run them in parallel across multiple workers.
> Test isolation is the default behavior in Playwright. Each `test()` automatically gets an independent `page` and `context`, requiring no additional configuration.
YouTip