QA Interview Hub · Knowledge base · Quizzes · Українська

Playwright › Browser, Context, Page

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

one browser, two contexts context alice session=A alicePage context bob session=B bobPage sends receives chat server (HTTP, WebSocket)
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 context
test('message reaches the recipient', async ({ page, context }) => {
  await login(page, 'alice');
  const second = await context.newPage();
  await login(second, 'bob');          // overwrites alice's session

  await page.goto('/chat/bob');        // now this is bob's session too
  await page.getByRole('textbox').fill('Hello');
  await page.getByRole('button', { name: 'Send' }).click();
  await expect(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.

// after: a context per user, the assertion on the recipient's side
import { test, expect } from '@playwright/test';

test('message reaches the recipient', async ({ browser }) => {
  const alice = await browser.newContext({ storageState: '.auth/alice.json' });
  const bob = await browser.newContext({ storageState: '.auth/bob.json' });
  const alicePage = await alice.newPage();
  const bobPage = await bob.newPage();

  try {
    await bobPage.goto('/chat/alice');   // Bob is already waiting in the chat
    await alicePage.goto('/chat/bob');
    await alicePage.getByRole('textbox').fill('Hello');
    await alicePage.getByRole('button', { name: 'Send' }).click();

    // no reload: the assertion waits for the message to arrive (e.g. over WebSocket)
    await expect(bobPage.getByText('Hello')).toBeVisible();
  } finally {
    await alice.close();
    await bob.close();
  }
});

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 2. Independent users need independent contexts.

A fixture for two roles. To avoid repeating context creation and forgetting to close it, move it into fixtures:

import { test as base, type Page } from '@playwright/test';

type Roles = { alicePage: Page; bobPage: Page };

export const test = base.extend<Roles>({
  alicePage: async ({ browser }, use) => {
    const ctx = await browser.newContext({ storageState: '.auth/alice.json' });
    await use(await ctx.newPage());
    await ctx.close();
  },
  bobPage: async ({ browser }, use) => {
    const ctx = await browser.newContext({ storageState: '.auth/bob.json' });
    await use(await ctx.newPage());
    await ctx.close();
  },
});

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 session
  await second.goto('/cabinet');

  await second.getByRole('button', { name: 'Log out' }).click();
  await page.reload();
  await expect(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 click
  await page.getByRole('link', { name: 'Terms' }).click();
  const popup = await popupPromise;
  await expect(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.

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.

More articles in this chapter