Skip to main content

Isolation

Tests written with Playwright execute in isolated clean-slate environments called browser contexts. This isolation model improves reproducibility and prevents cascading test failures.

BrowserContexts are equivalent to incognito-like profiles, they are fast and cheap to create and completely isolated, even when running in a single browser. Playwright creates a context for each test, and provides a default Page in that context.

When using Playwright as a Test Runner, this happens out of the box for each test. Otherwise, you can create browser contexts manually.

await using var browser = playwright.Chromium.LaunchAsync();
var context = await browser.NewContextAsync();
var page = await context.NewPageAsync();

Browser contexts can also be used to emulate multi-page scenarios involving mobile devices, permissions, locale and color scheme. Check out our Emulation guide for more details.

Multiple contexts in a single test

Playwright can create multiple browser contexts within a single scenario. This is useful when you want to test for multi-user functionality, like a chat.

using Microsoft.Playwright;
using System.Threading.Tasks;

class Program
{
public static async Task Main()
{
using var playwright = await Playwright.CreateAsync();
// Create a Chromium browser instance
await using var browser = await playwright.Chromium.LaunchAsync();
await using var userContext = await browser.NewContextAsync();
await using var adminContext = await browser.NewContextAsync();
// Create pages and interact with contexts independently.
}
}