How to Test Interactions Between Two Users in Playwright
In Playwright, if you create one context per user with browser.newContext(), you can log in two users separately and drive them in a single test. This is useful for E2E tests of features that depend on interactions between multiple users, such as a message sent in a chat reaching the other person, or a comment or approval request appearing on the other person's screen.
A context is a profile with its own cookies and local storage, similar to a private browsing window, and contexts do not share their contents with each other (the official documentation on test isolation). Here I prepared a small chat page where two users exchange messages, and checked how to write the test and where it is easy to get tripped up.
The test environment was Ubuntu 24.04, Node.js 22.23.5, and @playwright/test 1.63.0. Tests were written in TypeScript, using only headless Chromium, with one worker. The page under test is served by a small verification server written in Node.js (port 3100 on localhost). I did not try pages that receive messages over WebSocket, and I did not run the tests on Firefox or WebKit.
The chat page used for verification
When the server receives a request to /login?name=alice, it sets a cookie user=alice and shows a line reading "Logged in: alice" at the top of the page. When a message is sent, the server records the name in the cookie as the sender. The page refetches the message list every 0.5 seconds and displays it.
In the config file, I wrote baseURL and a webServer entry that starts the server.
// playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: './tests',
workers: 1,
use: {
baseURL: 'http://localhost:3100',
browserName: 'chromium',
},
webServer: {
command: 'node server.mjs',
url: 'http://localhost:3100/login?name=check',
},
});
Creating a context per user and driving both
I took browser instead of page as the test argument and called browser.newContext() twice to create contexts for alice and bob. This follows the same pattern as the official example of using multiple contexts in a single test.
// tests/chat.spec.ts
import { test, expect } from '@playwright/test';
test.beforeEach(async ({ request }) => {
await request.post('/reset');
});
test('alice の送ったメッセージが bob に届き、bob が返事をする', async ({ browser }) => {
const aliceContext = await browser.newContext();
const bobContext = await browser.newContext();
const alice = await aliceContext.newPage();
const bob = await bobContext.newPage();
await alice.goto('/login?name=alice');
await bob.goto('/login?name=bob');
await expect(alice.locator('#me')).toHaveText('ログイン中:alice');
await expect(bob.locator('#me')).toHaveText('ログイン中:bob');
await alice.getByLabel('メッセージを入力').fill('こんにちは');
await alice.getByRole('button', { name: '送信' }).click();
await expect(bob.getByRole('listitem')).toHaveText(['alice:こんにちは']);
await bob.getByLabel('メッセージを入力').fill('こんばんは');
await bob.getByRole('button', { name: '送信' }).click();
await expect(alice.getByRole('listitem')).toHaveText(['alice:こんにちは', 'bob:こんばんは']);
await aliceContext.close();
await bobContext.close();
});
In beforeEach, I call the verification server's /reset through request to empty the list, so that messages from a previous test do not remain.
When I ran it, the test passed in 1.2 seconds.
$ npx playwright test tests/chat.spec.ts --reporter=list
Running 1 test using 1 worker
✓ 1 tests/chat.spec.ts:7:1 › alice の送ったメッセージが bob に届き、bob が返事をする (1.2s)
1 passed (1.8s)
Even in contexts I created myself, alice.goto('/login?name=alice') with a relative path worked. The baseURL written in the use section of the config file was also passed to the contexts created with browser.newContext().
The assertion expect(bob.getByRole('listitem')).toHaveText(...), which checks the other user's screen, retries until it matches (the official list of auto-retrying assertions). The page refetches the list every 0.5 seconds, but the test passed without any waitForTimeout tuned to that interval.
I ran the same exchange in the two contexts and took screenshots. Each screen showed a different name at the top, and both lists contained both messages.

Opening two pages in one context swaps the sender
I also tried what happens when the contexts are not separated: I used the context test argument, called newPage() twice, and made one page for each user.
// tests/same-context.spec.ts (imports and beforeEach are the same as chat.spec.ts, so omitted)
test('同じコンテキストで2つのページを開くと', async ({ context }) => {
const alice = await context.newPage();
const bob = await context.newPage();
await alice.goto('/login?name=alice');
await bob.goto('/login?name=bob');
await expect(alice.locator('#me')).toHaveText('ログイン中:alice');
await alice.getByLabel('メッセージを入力').fill('こんにちは');
await alice.getByRole('button', { name: '送信' }).click();
await expect(bob.getByRole('listitem')).toHaveText(['alice:こんにちは']);
});
Alice's page showed the "Logged in: alice" line, so the first expect passed. However, the message sent from Alice's page arrived as "bob: Hello", and the test failed. Here is the part of the error output that shows the comparison.
Error: expect(locator).toHaveText(expected) failed
Locator: getByRole('listitem')
Timeout: 5000ms
- Expected - 1
+ Received + 1
Array [
- "alice:こんにちは",
+ "bob:こんにちは",
]
The two pages are in the same context, so there is only one set of cookies. When bob logged in, the user cookie was overwritten with bob, and the request sent from alice's page then carried bob's cookie. The screen still shows the state from when each user logged in, so the mix-up cannot be spotted from the display alone. When you drive two users, create one context per user, not one page per user.
Bundling the two users' pages into fixtures
To avoid writing the context setup for each user in every test, I also tried putting it into fixtures. Following the official example of role-based fixtures with POM, I created alice and bob fixtures.
// tests/users.ts
import { test as base, type Page } from '@playwright/test';
type Users = { alice: Page; bob: Page };
export const test = base.extend<Users>({
alice: async ({ browser }, use) => {
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('/login?name=alice');
await use(page);
await context.close();
},
bob: async ({ browser }, use) => {
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('/login?name=bob');
await use(page);
await context.close();
},
});
export { expect } from '@playwright/test';
The context.close() written after await use(page) runs as cleanup after the test finishes (the official explanation of fixture execution order). The test itself only receives alice and bob as arguments.
// tests/chat-fixture.spec.ts (beforeEach omitted)
import { test, expect } from './users';
test('bob の返事が alice に届く', async ({ alice, bob }) => {
await alice.getByLabel('メッセージを入力').fill('明日の会議は10時からです');
await alice.getByRole('button', { name: '送信' }).click();
await expect(bob.getByRole('listitem')).toHaveText(['alice:明日の会議は10時からです']);
await bob.getByLabel('メッセージを入力').fill('了解です');
await bob.getByRole('button', { name: '送信' }).click();
await expect(alice.getByRole('listitem').last()).toHaveText('bob:了解です');
});
test('alice だけを使うテストでは bob のブラウザは開かない', async ({ alice }) => {
await expect(alice.locator('#me')).toHaveText('ログイン中:alice');
expect(alice.context().browser()!.contexts()).toHaveLength(1);
});
The second test receives only alice as an argument, and counts how many contexts exist in the browser. The result was 1, and the unused bob fixture did not run. Fixtures are set up only for what a test needs. The official documentation on execution order also describes this.
$ npx playwright test tests/chat-fixture.spec.ts --reporter=list
Running 2 tests using 1 worker
✓ 1 tests/chat-fixture.spec.ts:7:1 › bob の返事が alice に届く (1.9s)
✓ 2 tests/chat-fixture.spec.ts:17:1 › alice だけを使うテストでは bob のブラウザは開かない (102ms)
2 passed (2.7s)
If going through the login screen in a real app takes a long time, you can also save each user's logged-in state (storageState) and pass it to browser.newContext(), as in the official example of running multiple roles together in one test.
When a test fails, screenshots and traces for both users remain
I also checked whether I could see what each user's screen looked like when a test failed. I created a separate config file that inherits the original settings and sets screenshot: 'only-on-failure' and trace: 'retain-on-failure' in use.
// fail.config.ts
import { defineConfig } from '@playwright/test';
import base from './playwright.config';
export default defineConfig(base, {
testDir: './tests-fail',
use: { screenshot: 'only-on-failure', trace: 'retain-on-failure' },
});
Using the fixtures above, I wrote a test that fails on purpose and ran it with npx playwright test -c fail.config.ts.
// tests-fail/fail.spec.ts (imports and beforeEach omitted; imported from '../tests/users')
test('失敗したときに2人分の画面が残るか', async ({ alice, bob }) => {
await alice.getByLabel('メッセージを入力').fill('こんにちは');
await alice.getByRole('button', { name: '送信' }).click();
await expect(bob.getByRole('listitem')).toHaveText(['alice:おはよう'], { timeout: 2000 });
});
The test results folder contained two screenshots and one trace file.
$ find test-results -type f | sort
test-results/.last-run.json
test-results/fail-失敗したときに2人分の画面が残るか/error-context.md
test-results/fail-失敗したときに2人分の画面が残るか/test-failed-1.png
test-results/fail-失敗したときに2人分の画面が残るか/test-failed-2.png
test-results/fail-失敗したときに2人分の画面が残るか/trace.zip
test-failed-1.png showed the "Logged in: alice" line and test-failed-2.png showed the "Logged in: bob" line. The contexts created with browser.newContext() inside the fixtures were also included in the screenshots.
When I unzipped trace.zip and looked inside, it contained records of two Chromium contexts. One recorded opening /login?name=alice and the other recorded opening /login?name=bob, so each user's actions were kept separately. The trace was not split per user; it was all in a single trace.zip.





