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

推荐订阅源

P
Privacy International News Feed
Martin Fowler
Martin Fowler
D
Docker
Y
Y Combinator Blog
云风的 BLOG
云风的 BLOG
U
Unit 42
T
Tailwind CSS Blog
J
Java Code Geeks
G
Google Developers Blog
MongoDB | Blog
MongoDB | Blog
阮一峰的网络日志
阮一峰的网络日志
WordPress大学
WordPress大学
月光博客
月光博客
大猫的无限游戏
大猫的无限游戏
美团技术团队
F
Fortinet All Blogs
N
News and Events Feed by Topic
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Hacker News - Newest:
Hacker News - Newest: "LLM"
The GitHub Blog
The GitHub Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Recorded Future
Recorded Future
N
Netflix TechBlog - Medium
Google DeepMind News
Google DeepMind News
Hacker News: Ask HN
Hacker News: Ask HN
L
LINUX DO - 最新话题
Microsoft Security Blog
Microsoft Security Blog
N
News and Events Feed by Topic
I
Intezer
TaoSecurity Blog
TaoSecurity Blog
NISL@THU
NISL@THU
小众软件
小众软件
博客园 - 聂微东
博客园 - Franky
有赞技术团队
有赞技术团队
P
Palo Alto Networks Blog
爱范儿
爱范儿
H
Hacker News: Front Page
C
Cyber Attacks, Cyber Crime and Cyber Security
C
Cisco Blogs
P
Proofpoint News Feed
I
InfoQ
Google DeepMind News
Google DeepMind News
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Vercel News
Vercel News
H
Heimdal Security Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
量子位

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
The Playwright Playbook — Part 3: Multi-User, Multi-Tab & Browser Context Testing
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