惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Recent Announcements
Recent Announcements
V
V2EX
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 聂微东
爱范儿
爱范儿
Jina AI
Jina AI
博客园 - Franky
IT之家
IT之家
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
T
Tailwind CSS Blog
博客园 - 三生石上(FineUI控件)
The Cloudflare Blog
M
MIT News - Artificial intelligence
aimingoo的专栏
aimingoo的专栏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
J
Java Code Geeks
人人都是产品经理
人人都是产品经理
腾讯CDC
博客园_首页
月光博客
月光博客
有赞技术团队
有赞技术团队
C
Check Point Blog
Microsoft Security Blog
Microsoft Security Blog
MyScale Blog
MyScale Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
The Playwright Playbook — Part 3: Multi-User, Multi-Tab &...
Faizal · 2026-06-17 · via DEV Community

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

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

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

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();
  }
}


🧩 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';

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')
  );
});


🔄 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();
});

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();
});


⚙️ 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/**'],
    },
  ],
});

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


🗺️ 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

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