DEV Community

Cover image for The Playwright Playbook β€” Part 3: Multi-User, Multi-Tab & Browser Context Testing
Faizal
Faizal

Posted on

The Playwright Playbook β€” Part 3: Multi-User, Multi-Tab & Browser Context Testing

The Playwright Playbook β€” Part 3: Multi-User, Multi-Tab & Browser Context Testing

"Most frameworks test one user at a time. Real apps don't work that way."

In Part 1, we built the full foundation β€” POM, storageState, fixtures, and a clean project structure. In Part 2, we took control of the network layer β€” mocking APIs, simulating failures, and asserting on real network calls.

Now we tackle the scenario that breaks most automation frameworks.

Multiple users. Simultaneously. In one test.

Think about your app for a moment. How many features actually involve just one user?

  • Admin assigns a task β†’ regular user sees it appear in real time
  • User A edits a record β†’ User B gets a notification
  • Admin revokes access β†’ User's session should invalidate
  • Two users try to edit the same record β†’ conflict resolution kicks in

These are real features. They need to be tested. And page.goto('/login') in a beforeEach won't get you there.

Playwright's browser context architecture was built exactly for this. Let's use it properly. 🎯


πŸ—οΈ Where We Left Off

After Part 2, our project looks like this:

playwright-playbook/
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ auth/
β”‚   β”‚   └── login.spec.ts                   βœ… Part 1
β”‚   β”œβ”€β”€ tasks/
β”‚   β”‚   └── task-management.spec.ts         βœ… Part 1
β”‚   └── network/                            βœ… Part 2
β”‚       β”œβ”€β”€ api-mocking.spec.ts
β”‚       β”œβ”€β”€ error-simulation.spec.ts
β”‚       └── network-assertions.spec.ts
β”œβ”€β”€ pages/
β”‚   β”œβ”€β”€ LoginPage.ts                        βœ… Part 1
β”‚   └── TaskPage.ts                         βœ… Part 1
β”œβ”€β”€ fixtures/
β”‚   β”œβ”€β”€ auth.fixture.ts                     βœ… Part 1
β”‚   β”œβ”€β”€ tasks.json                          βœ… Part 2
β”‚   β”œβ”€β”€ empty-tasks.json                    βœ… Part 2
β”‚   └── tasks-har.har                       βœ… Part 2
β”œβ”€β”€ scripts/
β”‚   └── record-har.ts                       βœ… Part 2
β”œβ”€β”€ .auth/
β”‚   β”œβ”€β”€ admin.json
β”‚   └── user.json
β”œβ”€β”€ global-setup.ts                         βœ… Part 1
β”œβ”€β”€ playwright.config.ts                    βœ… Part 1
└── .env
Enter fullscreen mode Exit fullscreen mode

By the end of Part 3, we add:

playwright-playbook/
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ multi-user/                         ← NEW
β”‚   β”‚   β”œβ”€β”€ role-permissions.spec.ts
β”‚   β”‚   └── realtime-collaboration.spec.ts
β”‚   └── multi-tab/                          ← NEW
β”‚       └── multi-tab-flows.spec.ts
β”œβ”€β”€ pages/
β”‚   └── DashboardPage.ts                    ← NEW
β”œβ”€β”€ fixtures/
β”‚   └── multi-user.fixture.ts               ← NEW
Enter fullscreen mode Exit fullscreen mode

Every one of these files will be fully built in this article. Let's understand the foundation first. πŸ‘‡


🧠 Understanding Browser Contexts β€” The Mental Model

This is the concept everything in this part is built on. Read it carefully.

In a regular browser, you have one session. One set of cookies. One logged-in user at a time.

Playwright has browser contexts β€” isolated browser environments that each have their own:

  • Cookies and session storage
  • Local storage
  • Authentication state
  • Network state
Browser (one instance)
β”œβ”€β”€ Context A  ← admin session (.auth/admin.json)
β”‚   └── Page A β†’ logged in as admin
└── Context B  ← user session (.auth/user.json)
    └── Page B β†’ logged in as regular user
Enter fullscreen mode Exit fullscreen mode

Both contexts run inside the same browser process. But they are completely isolated from each other β€” like two separate incognito windows, but programmable and controllable via Playwright.

This means you can have adminPage and userPage active in the same test, interacting with the same app simultaneously. 🀯


πŸ—οΈ Building the New Page Object β€” DashboardPage

Our Task Manager's dashboard is where task assignments, notifications, and real-time updates happen. We need a page object for it.

// pages/DashboardPage.ts
import { Page, Locator } from '@playwright/test';

export class DashboardPage {
  readonly page: Page;
  readonly taskList: Locator;
  readonly notificationBell: Locator;
  readonly notificationPanel: Locator;
  readonly welcomeMessage: Locator;
  readonly adminPanel: Locator;

  constructor(page: Page) {
    this.page = page;
    this.taskList = page.getByTestId('task-list');
    this.notificationBell = page.getByTestId('notification-bell');
    this.notificationPanel = page.getByTestId('notification-panel');
    this.welcomeMessage = page.getByTestId('welcome-message');
    this.adminPanel = page.getByTestId('admin-panel');
  }

  async goto() {
    await this.page.goto('/dashboard');
  }

  async waitForTaskToAppear(taskTitle: string) {
    await this.page
      .getByRole('listitem')
      .filter({ hasText: taskTitle })
      .waitFor({ state: 'visible' });
  }

  async openNotifications() {
    await this.notificationBell.click();
    await this.notificationPanel.waitFor({ state: 'visible' });
  }

  getNotificationLocator(text: string): Locator {
    return this.notificationPanel.getByText(text);
  }

  getTaskLocator(title: string): Locator {
    return this.page.getByRole('listitem').filter({ hasText: title });
  }

  async assignTaskToUser(taskTitle: string, userName: string) {
    const task = this.getTaskLocator(taskTitle);
    await task.hover();
    await task.getByRole('button', { name: 'Assign' }).click();
    await this.page.getByRole('option', { name: userName }).click();
  }
}
Enter fullscreen mode Exit fullscreen mode

🧩 Building the Multi-User Fixture

The auth.fixture.ts from Part 1 gives one authenticated page. For multi-user tests, we need two authenticated contexts running simultaneously.

This is where multi-user.fixture.ts comes in β€” it creates two independent browser contexts, each loaded with a different storageState, and hands both to the test as named fixtures.

// fixtures/multi-user.fixture.ts
import { test as base, Browser, BrowserContext, Page } from '@playwright/test';
import { TaskPage } from '../pages/TaskPage';
import { DashboardPage } from '../pages/DashboardPage';

type MultiUserFixtures = {
  adminContext: BrowserContext;
  userContext: BrowserContext;
  adminPage: Page;
  userPage: Page;
  adminTaskPage: TaskPage;
  userTaskPage: TaskPage;
  adminDashboard: DashboardPage;
  userDashboard: DashboardPage;
};

export const test = base.extend<MultiUserFixtures>({
  // Admin browser context β€” loaded with admin session
  adminContext: async ({ browser }, use) => {
    const context = await browser.newContext({
      storageState: '.auth/admin.json',
    });
    await use(context);
    await context.close();
  },

  // User browser context β€” loaded with regular user session
  userContext: async ({ browser }, use) => {
    const context = await browser.newContext({
      storageState: '.auth/user.json',
    });
    await use(context);
    await context.close();
  },

  // Admin page β€” a new page inside the admin context
  adminPage: async ({ adminContext }, use) => {
    const page = await adminContext.newPage();
    await use(page);
  },

  // User page β€” a new page inside the user context
  userPage: async ({ userContext }, use) => {
    const page = await userContext.newPage();
    await use(page);
  },

  // Admin TaskPage POM β€” ready to use
  adminTaskPage: async ({ adminPage }, use) => {
    const taskPage = new TaskPage(adminPage);
    await taskPage.goto();
    await use(taskPage);
  },

  // User TaskPage POM β€” ready to use
  userTaskPage: async ({ userPage }, use) => {
    const taskPage = new TaskPage(userPage);
    await taskPage.goto();
    await use(taskPage);
  },

  // Admin DashboardPage POM β€” ready to use
  adminDashboard: async ({ adminPage }, use) => {
    const dashboard = new DashboardPage(adminPage);
    await dashboard.goto();
    await use(dashboard);
  },

  // User DashboardPage POM β€” ready to use
  userDashboard: async ({ userPage }, use) => {
    const dashboard = new DashboardPage(userPage);
    await dashboard.goto();
    await use(dashboard);
  },
});

export { expect } from '@playwright/test';
Enter fullscreen mode Exit fullscreen mode

Now any test that needs two simultaneous users just imports from this fixture. The setup is invisible. The test reads like a story. 🎯


πŸ” Testing Role-Based Permissions

The first multi-user scenario: ensuring admin and regular user see different things in the same app.

// tests/multi-user/role-permissions.spec.ts
import { test, expect } from '../../fixtures/multi-user.fixture';

test('admin sees admin panel β€” regular user does not', async ({
  adminDashboard,
  userDashboard,
}) => {
  // Admin should see the admin panel
  await expect(adminDashboard.adminPanel).toBeVisible();

  // Regular user should NOT see the admin panel
  await expect(userDashboard.adminPanel).not.toBeVisible();
});

test('admin can delete any task β€” regular user can only delete their own', async ({
  adminTaskPage,
  userTaskPage,
  adminPage,
  userPage,
}) => {
  // Admin creates a task
  await adminTaskPage.createTask('Admin-owned task');

  // Admin can see and delete the task
  await expect(adminTaskPage.getTaskLocator('Admin-owned task')).toBeVisible();
  const adminDeleteBtn = adminPage
    .getByRole('listitem')
    .filter({ hasText: 'Admin-owned task' })
    .getByRole('button', { name: 'Delete' });
  await expect(adminDeleteBtn).toBeVisible();

  // Regular user can see the task but NOT delete it
  await userTaskPage.page.reload(); // reload to fetch latest tasks
  await expect(userTaskPage.getTaskLocator('Admin-owned task')).toBeVisible();
  const userDeleteBtn = userPage
    .getByRole('listitem')
    .filter({ hasText: 'Admin-owned task' })
    .getByRole('button', { name: 'Delete' });
  await expect(userDeleteBtn).not.toBeVisible();
});

test('admin can access /admin route β€” user gets redirected', async ({
  adminPage,
  userPage,
}) => {
  // Admin navigates to admin-only route
  await adminPage.goto('/admin');
  await expect(adminPage).toHaveURL('/admin');
  await expect(adminPage.getByRole('heading', { name: 'Admin Dashboard' })).toBeVisible();

  // Regular user is redirected away
  await userPage.goto('/admin');
  await expect(userPage).toHaveURL('/dashboard'); // redirected to their dashboard
  await expect(userPage.getByTestId('access-denied')).toBeVisible();
});

test('user count badge updates correctly per role', async ({
  adminDashboard,
  userDashboard,
}) => {
  // Admin sees all tasks across all users
  const adminCount = await adminDashboard.page
    .getByTestId('task-count-badge')
    .textContent();

  // Regular user only sees their own tasks β€” count should be lower or equal
  const userCount = await userDashboard.page
    .getByTestId('task-count-badge')
    .textContent();

  expect(parseInt(adminCount ?? '0')).toBeGreaterThanOrEqual(
    parseInt(userCount ?? '0')
  );
});
Enter fullscreen mode Exit fullscreen mode

πŸ”„ Testing Real-Time Collaboration

This is the scenario that's genuinely hard to test without Playwright's context architecture.

Admin creates or assigns a task. Regular user β€” in a separate browser context, watching the same app β€” should see it appear without refreshing.

// tests/multi-user/realtime-collaboration.spec.ts
import { test, expect } from '../../fixtures/multi-user.fixture';

test('task assigned by admin appears in real time for user', async ({
  adminDashboard,
  userDashboard,
}) => {
  // Both users are on the dashboard simultaneously
  // User is watching β€” no action yet

  // Admin assigns a task to the user
  await adminDashboard.assignTaskToUser('Fix flaky test in CI', 'Regular User');

  // User should see the task appear WITHOUT refreshing
  // waitForTaskToAppear polls until the element is visible (up to default timeout)
  await userDashboard.waitForTaskToAppear('Fix flaky test in CI');

  await expect(
    userDashboard.getTaskLocator('Fix flaky test in CI')
  ).toBeVisible();
});

test('user receives notification when task is assigned', async ({
  adminDashboard,
  userDashboard,
}) => {
  // Admin assigns a task
  await adminDashboard.assignTaskToUser('Write unit tests', 'Regular User');

  // User opens their notification panel
  await userDashboard.openNotifications();

  // Notification should appear in real time
  await expect(
    userDashboard.getNotificationLocator('You have been assigned: Write unit tests')
  ).toBeVisible();
});

test('task status update by admin reflects instantly for user', async ({
  adminTaskPage,
  userTaskPage,
}) => {
  // Admin marks a task as completed
  const taskItem = adminTaskPage.getTaskLocator('Review pull request');
  await taskItem.hover();
  await taskItem.getByRole('checkbox', { name: 'Mark complete' }).check();

  // User should see the task status update β€” no page refresh
  await expect(
    userTaskPage.getTaskLocator('Review pull request')
      .getByTestId('status-badge')
  ).toHaveText('Completed');
});

test('admin deleting a task removes it from user view in real time', async ({
  adminTaskPage,
  userTaskPage,
}) => {
  // Confirm both users can see the task first
  await expect(adminTaskPage.getTaskLocator('Fix flaky test in CI')).toBeVisible();
  await expect(userTaskPage.getTaskLocator('Fix flaky test in CI')).toBeVisible();

  // Admin deletes the task
  await adminTaskPage.deleteTask('Fix flaky test in CI');

  // Admin's view updates immediately
  await expect(adminTaskPage.getTaskLocator('Fix flaky test in CI')).not.toBeVisible();

  // User's view should also update β€” real-time sync
  await expect(userTaskPage.getTaskLocator('Fix flaky test in CI')).not.toBeVisible();
});
Enter fullscreen mode Exit fullscreen mode

This is what proper real-time feature testing looks like. Two users. One test. No mocking. No workarounds. Just Playwright doing what it was built for. πŸ’ͺ


πŸ—‚οΈ Testing Multi-Tab Flows

Browser contexts also power multi-tab testing β€” when your app opens links in new tabs, or when a workflow spans multiple browser windows.

The pattern is: listen for the new tab to open, wait for it, then interact with it just like any other page.

// tests/multi-tab/multi-tab-flows.spec.ts
import { test, expect } from '@playwright/test';
import { TaskPage } from '../../pages/TaskPage';
import { DashboardPage } from '../../pages/DashboardPage';

test('clicking task link opens detail view in new tab', async ({ page, context }) => {
  const taskPage = new TaskPage(page);
  await taskPage.goto();

  // Listen for the new tab BEFORE clicking the link that opens it
  const newTabPromise = context.waitForEvent('page');

  // Click a task that opens its detail in a new tab
  await taskPage.getTaskLocator('Write unit tests')
    .getByRole('link', { name: 'Open details' })
    .click();

  // Wait for and capture the new tab
  const newTab = await newTabPromise;
  await newTab.waitForLoadState('domcontentloaded');

  // Assert on the new tab
  await expect(newTab).toHaveURL(/\/tasks\/\d+/);
  await expect(newTab.getByRole('heading', { name: 'Write unit tests' })).toBeVisible();
  await expect(newTab.getByTestId('task-detail-panel')).toBeVisible();
});

test('completing a task in new tab updates the count on original tab', async ({
  page,
  context,
}) => {
  const dashboard = new DashboardPage(page);
  await dashboard.goto();

  // Capture pending task count on the original tab
  const initialCountText = await page.getByTestId('pending-count').textContent();
  const initialCount = parseInt(initialCountText ?? '0');

  // Open a task in a new tab
  const newTabPromise = context.waitForEvent('page');
  await dashboard.getTaskLocator('Write unit tests')
    .getByRole('link', { name: 'Open details' })
    .click();
  const taskDetailTab = await newTabPromise;
  await taskDetailTab.waitForLoadState('domcontentloaded');

  // Complete the task in the new tab
  await taskDetailTab.getByRole('button', { name: 'Mark as Complete' }).click();
  await expect(taskDetailTab.getByTestId('status-badge')).toHaveText('Completed');

  // Switch back to the original tab β€” count should have updated
  await page.bringToFront();
  await expect(page.getByTestId('pending-count')).toHaveText(
    String(initialCount - 1)
  );
});

test('authentication persists across new tabs in same context', async ({
  page,
  context,
}) => {
  // Start on dashboard (already authenticated via storageState)
  await page.goto('/dashboard');
  await expect(page.getByTestId('welcome-message')).toBeVisible();

  // Open a new tab within the same context
  const newTab = await context.newPage();
  await newTab.goto('/tasks');

  // Should still be authenticated β€” same context, same session
  await expect(newTab.getByTestId('task-list')).toBeVisible();
  await expect(newTab).not.toHaveURL('/login');
});

test('popup window flows work correctly', async ({ page }) => {
  const taskPage = new TaskPage(page);
  await taskPage.goto();

  // Some apps open popups (OAuth flows, print dialogs, confirm windows)
  // Listen for popup BEFORE triggering it
  const popupPromise = page.waitForEvent('popup');

  await page.getByRole('button', { name: 'Share task externally' }).click();
  const popup = await popupPromise;

  await popup.waitForLoadState('domcontentloaded');

  // Interact with the popup
  await expect(popup.getByRole('heading', { name: 'Share Task' })).toBeVisible();
  await popup.getByLabel('Recipient email').fill('colleague@company.com');
  await popup.getByRole('button', { name: 'Send' }).click();

  // Popup closes after sending
  await popup.waitForEvent('close');

  // Back on main page β€” confirm success message
  await expect(page.getByTestId('share-success-toast')).toBeVisible();
});
Enter fullscreen mode Exit fullscreen mode

βš™οΈ Updating playwright.config.ts for Multi-Context Tests

Multi-context tests need one small config addition β€” we need to make sure the browser fixture is available to our multi-user fixture (it is by default), and that parallel workers don't share state.

// playwright.config.ts β€” updated section
import { defineConfig, devices } from '@playwright/test';
import * as dotenv from 'dotenv';

dotenv.config();

export default defineConfig({
  testDir: './tests',
  fullyParallel: true,
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 1 : 0,
  workers: process.env.CI ? 4 : undefined,
  globalSetup: './global-setup.ts',

  reporter: [
    ['html', { open: 'never' }],
    ['list'],
  ],

  use: {
    baseURL: process.env.BASE_URL || 'http://localhost:3000',
    screenshot: 'only-on-failure',
    video: 'retain-on-failure',
    trace: 'on-first-retry',
  },

  projects: [
    {
      name: 'admin',
      use: {
        ...devices['Desktop Chrome'],
        storageState: '.auth/admin.json',
      },
      testMatch: ['**/auth/**', '**/tasks/**', '**/network/**'],
    },
    {
      name: 'user',
      use: {
        ...devices['Desktop Chrome'],
        storageState: '.auth/user.json',
      },
      testMatch: ['**/tasks/**'],
    },
    {
      // Multi-user and multi-tab tests manage their own contexts internally
      // so they don't inherit a storageState at the project level
      name: 'multi-context',
      use: {
        ...devices['Desktop Chrome'],
      },
      testMatch: ['**/multi-user/**', '**/multi-tab/**'],
    },
  ],
});
Enter fullscreen mode Exit fullscreen mode

The multi-context project has no storageState at the project level β€” because the multi-user.fixture.ts handles authentication per-context internally. πŸ”‘


πŸ“ Final Project Structure After Part 3

Every file listed below has been fully built across Parts 1, 2, and 3:

playwright-playbook/
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ auth/
β”‚   β”‚   └── login.spec.ts                        βœ… Part 1
β”‚   β”œβ”€β”€ tasks/
β”‚   β”‚   └── task-management.spec.ts              βœ… Part 1
β”‚   β”œβ”€β”€ network/                                 βœ… Part 2
β”‚   β”‚   β”œβ”€β”€ api-mocking.spec.ts
β”‚   β”‚   β”œβ”€β”€ error-simulation.spec.ts
β”‚   β”‚   └── network-assertions.spec.ts
β”‚   β”œβ”€β”€ multi-user/                              βœ… Part 3
β”‚   β”‚   β”œβ”€β”€ role-permissions.spec.ts
β”‚   β”‚   └── realtime-collaboration.spec.ts
β”‚   └── multi-tab/                              βœ… Part 3
β”‚       └── multi-tab-flows.spec.ts
β”œβ”€β”€ pages/
β”‚   β”œβ”€β”€ LoginPage.ts                             βœ… Part 1
β”‚   β”œβ”€β”€ TaskPage.ts                              βœ… Part 1
β”‚   └── DashboardPage.ts                         βœ… Part 3
β”œβ”€β”€ fixtures/
β”‚   β”œβ”€β”€ auth.fixture.ts                          βœ… Part 1
β”‚   β”œβ”€β”€ tasks.json                               βœ… Part 2
β”‚   β”œβ”€β”€ empty-tasks.json                         βœ… Part 2
β”‚   β”œβ”€β”€ tasks-har.har                            βœ… Part 2
β”‚   └── multi-user.fixture.ts                    βœ… Part 3
β”œβ”€β”€ scripts/
β”‚   └── record-har.ts                            βœ… Part 2
β”œβ”€β”€ .auth/                                       ← git-ignored, auto-generated
β”‚   β”œβ”€β”€ admin.json
β”‚   └── user.json
β”œβ”€β”€ global-setup.ts                              βœ… Part 1
β”œβ”€β”€ playwright.config.ts                         βœ… Part 1 (updated Part 3)
β”œβ”€β”€ .env                                         ← git-ignored
└── package.json
Enter fullscreen mode Exit fullscreen mode

πŸ—ΊοΈ What's Coming in This Series

Part 1 β€” Stop Writing Tests Like a Beginner              βœ… Done
Part 2 β€” Network Interception: The Complete Guide        βœ… Done
Part 3 β€” Multi-User, Multi-Tab & Context Testing         ← You are here
Part 4 β€” API Testing (The Underrated Superpower)
Part 5 β€” Visual Regression Testing
Part 6 β€” Debugging Like a Pro: Trace Viewer & Inspector
Part 7 β€” The CI/CD Setup Nobody Shows You
Part 8 β€” Playwright Meets AI: Agents, MCP & Self-Healing Tests
Enter fullscreen mode Exit fullscreen mode

In Part 4, we go into Playwright's request context β€” making raw API calls without a browser, schema validation, chaining API setup with UI assertions, and GraphQL testing. If you've ever used Postman for test automation, Part 4 will replace it entirely.


πŸ”– Before You Go

Multi-user and multi-tab testing is the feature that most QA engineers don't even attempt β€” because they assume it's too complex.

It isn't. It's three things:

  1. Two browser contexts with separate storageState
  2. A fixture that wires them both up cleanly
  3. Tests that treat both pages like normal Playwright pages

The complexity is in understanding the model. Once you have the model β€” the code is simple.

And now you have both. πŸ’ͺ


Follow me so you don't miss Part 4 β€” where we replace Postman with Playwright's API request context and build a proper API testing layer that talks directly to your backend without touching a browser.

Drop a comment below πŸ‘‡

  • Have you ever tried testing real-time features in Playwright before?
  • What's the most painful multi-user scenario in your app right now?
  • Did the browser context mental model click for you β€” or do you have questions?

Let's talk in the comments. πŸ™Œ


Faizal Shaikh | Senior Automation Engineer | Playwright & AI Testing
Connect with me on LinkedIn

Top comments (1)

Collapse
 
xulingfeng profile image
xulingfeng

Part 2 was waitForResponse, Part 3 is multi-context. You're building this series like a proper framework β€” each part stacks on the last. πŸ”₯
The real-time collab tests are what hit for me. Most multi-user demos fake it with mocked events β€” you just let two contexts talk through the actual app. Admin assigns β†’ user sees it live. No shortcuts. That's the real e2e gap most people don't cover.
You announced Part 4 as API Testing a while back β€” looking forward to seeing how that fits into the same fixture framework. πŸ‘€