The runner creates and closes the built-in fixtures itself, while a context created manually is closed by the test author. The browser is launched once per worker, and a fresh context and page are created for every test. A browser.newContext() context is used when another profile is needed and is closed in a fixture after await use(), so it closes even after a failure and videos and HARs are saved.
Playwright · Browser, Context, Page
A test asks only for page. So where does the context live, and who closes the one I created myself?
Almost every test starts with async ({ page }), which makes it easy to miss that three different objects with different lifetimes stand behind it. While one page is enough, this does not matter. Trouble starts when one test needs another locale, a second user, or a page without a saved login, and a failed test leaves no video in the report. This lesson explains who creates and closes what, and how to build your own contexts so that nothing leaks.
How it works and why. Browser, BrowserContext and Page are nested in each other. Browser is a running browser process, an expensive thing. BrowserContext is an isolated "profile" inside that browser, similar to an incognito window: its own cookies, localStorage, locale and time zone settings. Creating a context is cheap, many times faster than launching a browser. Page is a tab in a context.
Hence the runner's decision: the browser is launched once per worker and shared between tests (worker scope), while each test gets a fresh context and page (test scope). Tests are isolated at the session level without paying for a browser launch every time. One more detail: after a failed test the worker is shut down, and the next test runs in a new worker with a new browser. The runner does this to guarantee a clean state after a failure.
Who contains whom and how long it lives
Figure 1. One browser per worker, a context and a page per test. That is why tests do not see each other's cookies.
Fixture
Scope
Created
Closed by
browser
worker
Once per worker
Runner, after the worker
context
test
For every test
Runner, after the test
page
test
For every test, in context
Runner, with the context
The page fixture depends on context, and context on browser. So a test that asks only for page still has a context: you can get it by adding context to the parameter list, and it is the same object.
Context options. Most of what you write in the config's use is a context option (the rest controls the browser launch and the runner: headless, trace, testIdAttribute): baseURL, viewport, locale, timezoneId, storageState, permissions, extraHTTPHeaders, colorScheme, geolocation. For a file or a group you change them with test.use():
browser.newContext() accepts the same options. A context created by hand in a test also inherits the context options from use, and values passed explicitly to newContext override them.
Example: a custom context that leaks. One test needs another locale. The typical first version looks tidy but hides a problem:
// before: the context is closed only if the test reaches the endtest('guest sees the cookie banner', async ({ browser }) => {
const context = await browser.newContext({ locale: 'uk-UA' });
const page = await context.newPage();
await page.goto('/');
awaitexpect(page.getByRole('dialog', { name: 'Cookies' })).toBeVisible();
await context.close();
});
What is wrong here. If expect fails, it throws, and the context.close() line does not run. The runner does not treat a manually created context as its own, so closing it is the test author's job. Tabs stay open until the end of the worker. And if the context was given recordVideo or recordHar explicitly, the files are written only when it closes, so they may be missing for exactly the failed test. The config video option does not apply to manual contexts.
// after: closing in a fixture, teardown runs even after a failureimport { test as base, typeBrowserContext } from'@playwright/test';
exportconst test = base.extend<{ ukContext: BrowserContext }>({
ukContext: async ({ browser }, use) => {
const context = await browser.newContext({ locale: 'uk-UA' });
awaituse(context); // the test runs hereawait context.close(); // runs even if the test failed
},
});
Why this is right: the runner always executes the code after await use(), even when the test failed. A plain try/finally inside the test works too, but it must be repeated in every test. A fixture is written once, and the test just asks for ukContext and knows nothing about closing.
Built-in context or your own newContext
Better
Built-in context and test.use()
One user and one configuration for a test or a group. The runner creates and closes it, nothing leaks. Choose this by default.
Typical
browser.newContext() in a test
Needed only when one test has several profiles: another locale, another storageState, a second user. Closing becomes your debt, so hide it in a fixture.
Figure 2. A custom context is justified, but only where the built-in one does not fit.
Limits and alternatives. Context options apply to the whole context: locale, timezoneId and storageState do not change after creation, while, for example, the window size can be changed with page.setViewportSize(). If part of the tests needs another configuration, it is easier to move it to a separate project in the config than to create contexts by hand. In Selenium isolation usually means a separate WebDriver session or clearing cookies; in Cypress since version 12 testIsolation clears the page and cookies between tests by default. In Playwright isolation is built into the model, and a cheap context is its foundation.
Common mistakes.
Creating a context by hand without guaranteed closing: after a failure tabs stay open and recorded video or HAR are not finalised.
Calling chromium.launch() in a test instead of the browser fixture: every test pays for a browser launch, and the runner knows nothing about that browser.
Trying to change locale or storageState of an existing context: the options are set at creation.
Copying the same options into every newContext() instead of one place: the config, test.use() or a fixture.
Keeping state between tests in module variables because "the context is the same": it is fresh for each test, and only the browser is shared.
Check yourself
A test creates a context with browser.newContext(), and an expect in the middle fails. What happens to the context.close() line at the end, and why does it hurt?
Answer
The exception from expect interrupts the function, so close() never runs. Tabs stay open until the end of the worker, and the video and HAR of that context are finalised on close, so they may be missing for exactly the failed test. The fix: a fixture with close() after await use(), or try/finally.
Why do two tests in the same worker not see each other's cookies even though they use one browser?
Answer
Cookies and storage belong to the context, not the browser. Each test gets a new context, and the browser is only a container in which contexts are isolated from each other. The browser is shared for speed, and isolation comes from contexts.
Related lessons: "Playwright architecture and test isolation", "Fixtures and scopes", "Authentication: storageState and a setup project", "Two users in one test".
In an interview.Junior: Browser is launched once per worker, while context and page are created for each test and closed automatically. A context is an isolated profile with its own cookies and storage. Middle/Senior: I create my own context with browser.newContext() only when a test needs a different profile, and I close it in a fixture after await use(), so teardown runs even on failure and the video and HAR are kept. I would not launch a browser inside a test: it is expensive and goes around worker management.
Two users in one test
Two users in one test need two BrowserContexts with separate storageState, not two tabs. Cookies and storage belong to the context, so pages of one context share one session and a second login overwrites it. Contexts live in one browser and are cheap. Several pages of one context are used only for single-user scenarios.
Playwright · Browser, Context, Page
Two users in one test: a second tab or a second context? The second login overwrites the first one's session.
A chat, a shared document, a transfer between two accounts, moderation: in these scenarios two people act in one test. The intuitive move is to open a second tab and treat it as "another person", but a tab is not a person. If both logins went through one context, the sessions overwrote each other, and the test checks a user talking to themselves. This lesson is about choosing between several contexts and several pages of one context.
How it works and why. Cookies and storage belong to the context, not the page. All pages of one context share one cookie "jar", so a second login simply overwrites the session cookie of the first. Independent sessions are separate BrowserContexts. They all live in one browser, so a second browser is not needed: a context costs little. Each context gets its own storageState, so the user is logged in right away without going through the form. A storageState file is a snapshot of cookies and localStorage at the moment it was saved: once a context is created, the two copies develop independently.
Who shares a session with whom
Figure 1. The two sessions do not see each other in the browser: users connect only through the server, as in reality.
Example: a test that is green and proves nothing. The first version often looks like this:
// before: two "users" in one contexttest('message reaches the recipient', async ({ page, context }) => {
awaitlogin(page, 'alice');
const second = await context.newPage();
awaitlogin(second, 'bob'); // overwrites alice's sessionawait page.goto('/chat/bob'); // now this is bob's session tooawait page.getByRole('textbox').fill('Hello');
await page.getByRole('button', { name: 'Send' }).click();
awaitexpect(page.getByText('Hello')).toBeVisible();
});
What is wrong here. After Bob's login the context's cookies hold his session, so the first tab is "Bob" too. The result depends on the order of actions, and the assertion sees a message the user has just sent themselves, so it passes even if nothing was delivered to the recipient. The test is green without any proof of delivery.
Context: A context per user: separate cookies and storage, so the sessions of alice and bob do not overwrite each other.
Recipient: Bob opens the chat first and waits for the message.
Assertion: The check on the recipient side without a reload or pauses: the web-first assertion waits until the message arrives.
finally: Both contexts are closed even if the test failed.
Figure 2. The numbers lead to the explanations of the code lines.
Why this is right: the two sessions are truly independent, and the assertion sits on Bob's side, so it checks delivery itself. Bob opens the chat before sending, which verifies "live" delivery. Had he opened it afterwards, the test would only check the message history.
One context or two
Typical
Two pages of one context for two people
Cookies are shared, the second login overwrites the first. The test is falsely green or fails at a random place.
Better
A context per user
Separate sessions, own storageState, closing the contexts is explicit. Cheap: one browser.
Figure 3. Independent users need independent contexts.
A fixture for two roles. To avoid repeating context creation and forgetting to close it, move it into fixtures:
Fixtures are lazy: a test that asks only for alicePage does not create Bob's context.
The opposite case: several pages of one context. When one user is checked in several tabs, shared cookies are the very thing under test: a logout in one tab must sign out the other, a cart syncs between tabs. A tab opened by the application itself is caught before the action:
test('logout in one tab signs out the other', async ({ context, page }) => {
await page.goto('/cabinet');
const second = await context.newPage(); // the same sessionawait second.goto('/cabinet');
await second.getByRole('button', { name: 'Log out' }).click();
await page.reload();
awaitexpect(page).toHaveURL(/\/login/);
});
test('a link opens in a new tab', async ({ page, context }) => {
await page.goto('/help');
const popupPromise = context.waitForEvent('page'); // subscribe before the clickawait page.getByRole('link', { name: 'Terms' }).click();
const popup = await popupPromise;
awaitexpect(popup).toHaveURL(/terms/);
});
Limits and alternatives. The second user does not always need to go through the browser: if only the first user's UI reaction is checked, the second action can be an API call via the request fixture or playwright.request.newContext(). That is faster and more stable but does not verify the second user's UI. Selenium needs two driver sessions for two users, and in Cypress a test normally runs in one tab, so the other side is more often replaced by an API request. One more limit: parallel workers using the same accounts get mixed up. A parallel run needs unique users or separate chats per test.
Common mistakes.
Logging two users into one context: the sessions overwrite each other, and the test fails or passes as one of them.
Launching a second browser for the second user: extra seconds and memory when a context is enough.
Checking delivery with waitForTimeout or reload instead of a web-first assertion: a pause guarantees nothing, and a reload replaces "live" with history.
Not closing contexts on failure: tabs hang around, and an explicitly enabled recordVideo is not finalised.
Using the same accounts in parallel workers: tests write to one chat at the same time and interfere with each other.
Check yourself
A test logged alice in on page, then logged bob in on context.newPage() and checks that alice sees a message from bob. Why does the result prove nothing?
Answer
Both pages of one context share cookies, so after bob's login alice's session is overwritten and the first tab acts as bob too. The "message from bob to alice" really goes from bob to bob, and the assertion can pass for any reason. You need two contexts with separate storageState.
Why is the delivery assertion on bobPage, and why does Bob open the chat before Alice?
Answer
Delivery is confirmed by what the recipient sees, so the assertion belongs on their page. If Bob opens the chat after the message is sent, he sees it from the history, and the test does not verify "live" delivery, for example over WebSocket.
Related lessons: "Playwright architecture and test isolation", "Built-in fixtures and manual creation", "Several roles and the logged-out state", "Parallelism, workers and sharding".
In an interview.Junior: For two users I create two contexts with different storageState, because a context is a separate session. Pages of one context share cookies. Middle/Senior: I use several pages of one context only for single-user scenarios, such as a logout across two tabs. I move contexts into fixtures so they are closed on failure, and I check delivery with a web-first assertion on the recipient's side. For parallel runs I plan unique users per worker, and sometimes replace the second side with an API call to keep the test faster.
Page events as an extra check
Page and BrowserContext emit events that expose what the UI does not show. These are pageerror for unhandled exceptions, console for the console, response for 404 and 500 statuses. Subscribe before the action, because an event that has passed is lost to the code. A response with an error status is not requestfailed: that event covers only network-level failures.
Playwright · Browser, Context, Page
The UI assertions are green, yet the console is red. How can a test see what is not on screen?
The payment test passed: the button was clicked, the confirmation is on screen. Yet the browser console shows an unhandled exception, a third-party script answered 500, and the analytics load was cut off. The user does not see this until something nearby breaks. Page and BrowserContext emit events you can subscribe to, and that is how a test gets access to everything that happens outside the visible UI. This lesson covers which events there are, when to subscribe, and how to make the check automatic.
How it works and why. Playwright watches the page through the browser protocol and delivers every event (a console message, a network request, a dialog) to the Node.js test process. An event does not wait for the test: it arrives when it happens, and if there is no handler at that moment, it is simply lost to your code. Hence two rules. Subscribe before the action that triggers the event. And remember that events arrive asynchronously, so check what you collected only after the UI has reached the expected state.
Page events: console, pageerror, request, response, requestfailed, requestfinished, dialog, popup, download, filechooser, websocket, frameattached. Many of them exist at the BrowserContext level for all pages at once, plus the page event for new tabs.
What happened
Which event
Unhandled exception in the page's JS
pageerror
The code itself called console.error()
console, type error
A request failed at the network level (reset, CORS, DNS)
requestfailed
The server answered 404 or 500
response with a status
alert, confirm, prompt
dialog
A new tab from the page
popup
A file download
download
An important limit: a 404 or 500 response is not a requestfailed. The request finished successfully, just with an error status, so you catch it through response.
When to check the collected errors
Figure 1. Events arrive asynchronously, so assert on the collected array after waiting for the UI, not right after the action.
Example: the UI is green, the errors are invisible. The first version of the test checks only the screen:
// before: checking only what is visibletest('payment goes through', async ({ page }) => {
await page.goto('/checkout');
await page.getByRole('button', { name: 'Pay' }).click();
awaitexpect(page.getByText('Thank you for your order')).toBeVisible();
});
The test is green although after the click the page threw a TypeError in the script that sends an analytics event, and the reviews widget answered 500. The UI assertion knows nothing about it. Subscribing to events fixes that:
pageerror: An unhandled exception in the page code.
console: Only messages of the error level, so warnings do not turn the test red.
5xx: Server responses with status 500 and above: the interface may swallow them.
Check: The array is checked at the end, when the UI has reached the needed state. The test fails with the list of all problems.
Figure 2. The numbers lead to the explanations of the code lines.
How to read it.pageerror is an exception nobody caught, while console with type error is what the code itself printed through console.error. The second stream is often noisy: trackers, extensions, third-party widgets. So the array is usually filtered for known noise, and the test fails only on what belongs to the product. The assertion on the empty array comes after toBeVisible, not right after click() (figure 1).
Events that demand a reaction. Some events are not just observed, they block the page. If there is no dialog handler at all, alert, confirm and prompt are dismissed automatically. If there is one, it must call accept() or dismiss() itself, or the page will hang. A new tab and a download are awaited through waitForEvent, creating the promise before the click:
Check the dialog text outside the handler: an exception inside an event handler does not always stop the test the way you expect.
An auto fixture instead of copying. To avoid duplicating the collection in every test, move it into a fixture with auto: true: it runs for every test by itself, subscribes at the start and checks the result in teardown:
import { test as base, expect } from'@playwright/test';
exportconst test = base.extend<{ jsErrors: void }>({
jsErrors: [
async ({ page }, use) => {
const errors: string[] = [];
page.on('pageerror', (err) => errors.push(err.message));
awaituse();
expect(errors, 'unhandled JS errors on the page').toEqual([]);
},
{ auto: true },
],
});
Subscribing before or after the action
Typical
After the action
click(), then page.on('dialog') or waitForEvent. The event already happened with no handler: the dialog closed by itself, and waitForEvent waits until the timeout.
Better
Before the action
First the handler or the waitForEvent promise, then click(). The event is guaranteed to reach the test code.
Figure 3. The order of subscribing and acting decides whether the test sees the event.
Limits and alternatives. Collecting events shows symptoms, not the cause: to see what happened on the page before a failure, look at the trace. A console subscription sees only the page's console, not server logs. A hard "no console errors" rule for a whole page makes the test depend on third-party scripts, so combine it with an allow-list of known exceptions. For the network, when you need to replace or block rather than observe, use page.route() (a separate topic). In Cypress any unhandled exception fails the test by default, and cy.on('uncaught:exception') configures that behaviour. Playwright has no such behaviour, and you add it yourself.
Common mistakes.
Subscribing after the action that triggers the event: the event has already happened, waitForEvent hangs until the timeout, and the dialog was closed automatically.
Asserting the error array right after a click without waiting for the UI state: a late error slips through.
Expecting requestfailed to fire on HTTP 500: that is a response event with a status.
Not filtering third-party noise: the test fails for reasons unrelated to the product.
Adding a dialog handler and not calling accept() or dismiss(): the page waits for an answer and hangs.
Check yourself
A test does click(), immediately expect(errors).toEqual([]), and only then waits for the confirmation text. A JS error arrives 200 ms after the click. What will the test show and how do you fix it?
Answer
The array is still empty, so the check passes, and the error appears after it and stops nobody. First wait for the UI state (toBeVisible), and only then assert the array. Then the event will almost certainly have arrived.
The server returned 502 for a third-party widget. Will page.on('requestfailed') fire, and which event do you need?
Answer
No. The request finished successfully, just with status 502, while requestfailed describes a network-level failure: a reset, a block, DNS. Check the status in a response handler through res.status().
Related lessons: "Web-first assertions", "Observe or replace: waitForResponse, waitForRequest, route", "Fixtures and scopes", "Diagnostics: trace viewer, reports, flaky tests".
In an interview.Junior: I subscribe to pageerror and console to see JS errors that UI assertions do not catch, and I wait for dialogs, new tabs and downloads through a handler or a waitForEvent created before the click. Middle/Senior: I move error collection into an auto fixture that checks for an empty array after the test, with a filter for known noise. I catch error statuses through response, because requestfailed does not see them. I place the assertion after waiting for the UI, because events arrive asynchronously.