@scenarist/playwright-helpers 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,12 +9,12 @@ Playwright test helpers for [Scenarist](https://scenarist.io) scenario managemen
9
9
 
10
10
  **Full documentation at [scenarist.io](https://scenarist.io)**
11
11
 
12
- | Topic | Link |
13
- |-------|------|
14
- | **Why Scenarist?** | [scenarist.io/introduction/why-scenarist](https://scenarist.io/introduction/why-scenarist) |
12
+ | Topic | Link |
13
+ | -------------------------- | -------------------------------------------------------------------------------------------------- |
14
+ | **Why Scenarist?** | [scenarist.io/getting-started/why-scenarist](https://scenarist.io/getting-started/why-scenarist) |
15
15
  | **Playwright Integration** | [scenarist.io/testing/playwright-integration](https://scenarist.io/testing/playwright-integration) |
16
- | **Parallel Testing** | [scenarist.io/testing/parallel-testing](https://scenarist.io/testing/parallel-testing) |
17
- | **Testing Philosophy** | [scenarist.io/concepts/philosophy](https://scenarist.io/concepts/philosophy) |
16
+ | **Parallel Testing** | [scenarist.io/testing/parallel-testing](https://scenarist.io/testing/parallel-testing) |
17
+ | **Testing Philosophy** | [scenarist.io/concepts/philosophy](https://scenarist.io/concepts/philosophy) |
18
18
 
19
19
  ## Installation
20
20
 
@@ -32,6 +32,7 @@ yarn add -D @scenarist/playwright-helpers
32
32
  ## Quick Start (Recommended: Fixtures API)
33
33
 
34
34
  The **fixtures API** is the recommended way to use Scenarist with Playwright. It provides:
35
+
35
36
  - ✅ Guaranteed unique test IDs (no collisions, even with parallel execution)
36
37
  - ✅ Configuration in one place (no repetition across tests)
37
38
  - ✅ Clean composition with your existing fixtures
@@ -40,30 +41,44 @@ The **fixtures API** is the recommended way to use Scenarist with Playwright. It
40
41
  ### 1. Configure in `playwright.config.ts`
41
42
 
42
43
  ```typescript
43
- import { defineConfig } from '@playwright/test';
44
- import type { ScenaristOptions } from '@scenarist/playwright-helpers';
44
+ import { defineConfig } from "@playwright/test";
45
+ import type { ScenaristOptions } from "@scenarist/playwright-helpers";
45
46
 
46
47
  export default defineConfig<ScenaristOptions>({
47
48
  use: {
48
- baseURL: 'http://localhost:3000', // Standard Playwright config
49
- scenaristEndpoint: '/api/__scenario__', // Scenarist-specific config
49
+ baseURL: "http://localhost:3000", // Standard Playwright config
50
+ scenaristEndpoint: "/api/__scenario__", // Scenarist-specific config
50
51
  },
51
52
  });
52
53
  ```
53
54
 
54
55
  **Note:** The `<ScenaristOptions>` type parameter enables TypeScript to recognize `scenaristEndpoint` as a valid configuration option.
55
56
 
56
- ### 2. Use in Tests
57
+ ### 2. Create a Fixtures File
58
+
59
+ Create `tests/fixtures.ts` with your scenarios:
60
+
61
+ ```typescript
62
+ // tests/fixtures.ts
63
+ import { withScenarios, expect } from "@scenarist/playwright-helpers";
64
+ import { scenarios } from "../lib/scenarios"; // Your scenario definitions
65
+
66
+ export const test = withScenarios(scenarios);
67
+ export { expect };
68
+ ```
69
+
70
+ ### 3. Use in Tests
57
71
 
58
72
  ```typescript
59
- import { test, expect } from '@scenarist/playwright-helpers';
73
+ // tests/my-test.spec.ts
74
+ import { test, expect } from "./fixtures"; // Import from YOUR fixtures file
60
75
 
61
- test('premium user sees premium pricing', async ({ page, switchScenario }) => {
76
+ test("premium user sees premium pricing", async ({ page, switchScenario }) => {
62
77
  // Configuration read from playwright.config.ts - no repetition!
63
- await switchScenario(page, 'premiumUser');
78
+ await switchScenario(page, "premiumUser"); // Type-safe! Autocomplete works
64
79
 
65
- await page.goto('/');
66
- await expect(page.getByRole('heading', { name: 'Premium' })).toBeVisible();
80
+ await page.goto("/");
81
+ await expect(page.getByRole("heading", { name: "Premium" })).toBeVisible();
67
82
  });
68
83
  ```
69
84
 
@@ -75,20 +90,22 @@ If your team already has custom Playwright fixtures, you can easily compose them
75
90
 
76
91
  ```typescript
77
92
  // tests/fixtures.ts
78
- import { test as scenaristTest } from '@scenarist/playwright-helpers';
93
+ import { withScenarios, expect } from "@scenarist/playwright-helpers";
94
+ import { scenarios } from "../lib/scenarios";
95
+ import type { Page } from "@playwright/test";
79
96
 
80
97
  type MyFixtures = {
81
98
  authenticatedPage: Page;
82
99
  database: Database;
83
100
  };
84
101
 
85
- export const test = scenaristTest.extend<MyFixtures>({
102
+ export const test = withScenarios(scenarios).extend<MyFixtures>({
86
103
  authenticatedPage: async ({ page }, use) => {
87
104
  // Your custom fixture logic
88
- await page.goto('/login');
89
- await page.fill('[name=email]', 'test@example.com');
90
- await page.fill('[name=password]', 'password');
91
- await page.click('button[type=submit]');
105
+ await page.goto("/login");
106
+ await page.fill("[name=email]", "test@example.com");
107
+ await page.fill("[name=password]", "password");
108
+ await page.click("button[type=submit]");
92
109
  await use(page);
93
110
  },
94
111
 
@@ -99,54 +116,55 @@ export const test = scenaristTest.extend<MyFixtures>({
99
116
  },
100
117
  });
101
118
 
102
- export { expect } from '@scenarist/playwright-helpers';
119
+ export { expect };
103
120
  ```
104
121
 
105
122
  Now use your extended test object:
106
123
 
107
124
  ```typescript
108
125
  // tests/my-test.spec.ts
109
- import { test, expect } from './fixtures';
126
+ import { test, expect } from "./fixtures";
110
127
 
111
- test('authenticated premium user flow', async ({ authenticatedPage, switchScenario, database }) => {
128
+ test("authenticated premium user flow", async ({
129
+ authenticatedPage,
130
+ switchScenario,
131
+ database,
132
+ }) => {
112
133
  // All fixtures available: yours + Scenarist's
113
- await switchScenario(authenticatedPage, 'premiumUser');
114
- await authenticatedPage.goto('/dashboard');
134
+ await switchScenario(authenticatedPage, "premiumUser");
135
+ await authenticatedPage.goto("/dashboard");
115
136
 
116
- const user = await database.getUser('test@example.com');
117
- expect(user.tier).toBe('premium');
137
+ const user = await database.getUser("test@example.com");
138
+ expect(user.tier).toBe("premium");
118
139
  });
119
140
  ```
120
141
 
121
- ## Type-Safe Scenario IDs (Optional but Recommended)
142
+ ## Type-Safe Scenario IDs (Automatic)
122
143
 
123
- Get autocomplete and type checking for scenario names:
144
+ Type safety is **automatic** when you use `withScenarios(scenarios)`. The function infers scenario IDs from your scenarios object.
124
145
 
125
- ### 1. Define Scenarios with Type Export
146
+ ### 1. Define Scenarios
126
147
 
127
148
  ```typescript
128
149
  // lib/scenarios.ts
129
- import type { ScenaristScenario, ScenaristScenarios } from '@scenarist/core';
150
+ import type { ScenaristScenarios } from '@scenarist/core';
130
151
 
131
152
  export const scenarios = {
132
- cartWithState: { id: 'cartWithState', name: 'Cart with State', ... },
133
- premiumUser: { id: 'premiumUser', name: 'Premium User', ... },
134
- standardUser: { id: 'standardUser', name: 'Standard User', ... },
153
+ cartWithState: { id: 'cartWithState', name: 'Cart with State', mocks: [...] },
154
+ premiumUser: { id: 'premiumUser', name: 'Premium User', mocks: [...] },
155
+ standardUser: { id: 'standardUser', name: 'Standard User', mocks: [...] },
135
156
  } as const satisfies ScenaristScenarios;
136
-
137
- // Derive type from actual scenarios (or use ScenarioIds<typeof scenarios>)
138
- export type ScenarioId = keyof typeof scenarios;
139
157
  ```
140
158
 
141
159
  ### 2. Create Typed Test Object
142
160
 
143
161
  ```typescript
144
162
  // tests/fixtures.ts
145
- import { createTest, expect } from '@scenarist/playwright-helpers';
146
- import type { ScenarioId } from '../lib/scenarios';
163
+ import { withScenarios, expect } from "@scenarist/playwright-helpers";
164
+ import { scenarios } from "../lib/scenarios";
147
165
 
148
- // Create typed test object with your scenario IDs
149
- export const test = createTest<ScenarioId>();
166
+ // Type-safe test object - scenario IDs are inferred automatically!
167
+ export const test = withScenarios(scenarios);
150
168
  export { expect };
151
169
  ```
152
170
 
@@ -154,17 +172,18 @@ export { expect };
154
172
 
155
173
  ```typescript
156
174
  // tests/my-test.spec.ts
157
- import { test, expect } from './fixtures';
175
+ import { test, expect } from "./fixtures";
158
176
 
159
- test('my test', async ({ page, switchScenario }) => {
160
- await switchScenario(page, 'cart'); // ❌ TypeScript error: not a valid scenario
161
- await switchScenario(page, 'cartWithState'); // ✅ Autocomplete works!
177
+ test("my test", async ({ page, switchScenario }) => {
178
+ await switchScenario(page, "cart"); // ❌ TypeScript error: not a valid scenario
179
+ await switchScenario(page, "cartWithState"); // ✅ Autocomplete works!
162
180
  // ^
163
181
  // Autocomplete shows all valid scenario IDs
164
182
  });
165
183
  ```
166
184
 
167
185
  **Benefits:**
186
+
168
187
  - ✅ Autocomplete shows all valid scenario names
169
188
  - ✅ TypeScript errors for typos or invalid scenarios
170
189
  - ✅ Type stays in sync with actual scenarios (single source of truth)
@@ -175,13 +194,13 @@ test('my test', async ({ page, switchScenario }) => {
175
194
  Most tests use the global config, but you can override for specific tests:
176
195
 
177
196
  ```typescript
178
- test('staging environment test', async ({ page, switchScenario }) => {
179
- await switchScenario(page, 'myScenario', {
180
- baseURL: 'https://staging.example.com', // Override for this test only
181
- endpoint: '/api/custom-endpoint',
197
+ test("staging environment test", async ({ page, switchScenario }) => {
198
+ await switchScenario(page, "myScenario", {
199
+ baseURL: "https://staging.example.com", // Override for this test only
200
+ endpoint: "/api/custom-endpoint",
182
201
  });
183
202
 
184
- await page.goto('/');
203
+ await page.goto("/");
185
204
  // Test against staging environment
186
205
  });
187
206
  ```
@@ -191,19 +210,19 @@ test('staging environment test', async ({ page, switchScenario }) => {
191
210
  For cases where you need manual control over test IDs or can't use fixtures:
192
211
 
193
212
  ```typescript
194
- import { test, expect } from '@playwright/test';
195
- import { switchScenario } from '@scenarist/playwright-helpers';
213
+ import { test, expect } from "@playwright/test";
214
+ import { switchScenario } from "@scenarist/playwright-helpers";
196
215
 
197
- test('premium user scenario', async ({ page }) => {
216
+ test("premium user scenario", async ({ page }) => {
198
217
  // Switch to premium scenario (generates unique test ID, sets headers automatically)
199
- await switchScenario(page, 'premiumUser', {
200
- baseURL: 'http://localhost:3000',
201
- endpoint: '/api/__scenario__',
218
+ await switchScenario(page, "premiumUser", {
219
+ baseURL: "http://localhost:3000",
220
+ endpoint: "/api/__scenario__",
202
221
  });
203
222
 
204
223
  // Navigate and test as premium user
205
- await page.goto('/');
206
- await expect(page.locator('.premium-badge')).toBeVisible();
224
+ await page.goto("/");
225
+ await expect(page.locator(".premium-badge")).toBeVisible();
207
226
  });
208
227
  ```
209
228
 
@@ -213,16 +232,19 @@ test('premium user scenario', async ({ page }) => {
213
232
 
214
233
  ```typescript
215
234
  type SwitchScenarioOptions = {
216
- readonly baseURL: string; // Base URL of your application
217
- readonly endpoint?: string; // Scenario endpoint path (default: '/__scenario__')
218
- readonly testIdHeader?: string; // Test ID header name (default: 'x-scenarist-test-id')
219
- readonly variant?: string; // Optional scenario variant
235
+ readonly baseURL: string; // Base URL of your application
236
+ readonly endpoint?: string; // Scenario endpoint path or absolute URL (default: '/__scenario__')
237
+ readonly testIdHeader?: string; // Test ID header name (default: 'x-scenarist-test-id')
238
+ readonly variant?: string; // Optional scenario variant
220
239
  };
221
240
  ```
222
241
 
242
+ > **Tip:** Use an absolute URL for `endpoint` when your API runs on a different host/port than the frontend. See [Cross-Origin API Servers](#cross-origin-api-servers).
243
+
223
244
  #### What it does
224
245
 
225
246
  The `switchScenario` helper:
247
+
226
248
  1. Generates a unique test ID (`test-{scenarioId}-{timestamp}`)
227
249
  2. POSTs to the scenario endpoint with the test ID header
228
250
  3. Verifies the scenario switch succeeded (200 response)
@@ -231,21 +253,26 @@ The `switchScenario` helper:
231
253
  This reduces scenario switching from 9 lines of boilerplate to 2 lines:
232
254
 
233
255
  **Without helper (9 lines):**
256
+
234
257
  ```typescript
235
258
  const testId = `test-premium-${Date.now()}`;
236
- const response = await page.request.post('http://localhost:3000/api/__scenario__', {
237
- headers: { 'x-scenarist-test-id': testId },
238
- data: { scenario: 'premiumUser' },
239
- });
259
+ const response = await page.request.post(
260
+ "http://localhost:3000/api/__scenario__",
261
+ {
262
+ headers: { "x-scenarist-test-id": testId },
263
+ data: { scenario: "premiumUser" },
264
+ },
265
+ );
240
266
  expect(response.status()).toBe(200);
241
- await page.setExtraHTTPHeaders({ 'x-scenarist-test-id': testId });
267
+ await page.setExtraHTTPHeaders({ "x-scenarist-test-id": testId });
242
268
  ```
243
269
 
244
270
  **With helper (2 lines):**
271
+
245
272
  ```typescript
246
- await switchScenario(page, 'premiumUser', {
247
- baseURL: 'http://localhost:3000',
248
- endpoint: '/api/__scenario__',
273
+ await switchScenario(page, "premiumUser", {
274
+ baseURL: "http://localhost:3000",
275
+ endpoint: "/api/__scenario__",
249
276
  });
250
277
  ```
251
278
 
@@ -255,14 +282,24 @@ await switchScenario(page, 'premiumUser', {
255
282
 
256
283
  ### Fixtures API (Recommended)
257
284
 
258
- #### `test`
285
+ #### `withScenarios(scenarios)`
286
+
287
+ Creates a type-safe Playwright test object with Scenarist fixtures.
288
+
289
+ ```typescript
290
+ // tests/fixtures.ts
291
+ import { withScenarios, expect } from "@scenarist/playwright-helpers";
292
+ import { scenarios } from "../lib/scenarios";
259
293
 
260
- Extended Playwright test object with Scenarist fixtures.
294
+ export const test = withScenarios(scenarios);
295
+ export { expect };
296
+ ```
261
297
 
262
298
  ```typescript
263
- import { test } from '@scenarist/playwright-helpers';
299
+ // tests/my-test.spec.ts
300
+ import { test, expect } from "./fixtures";
264
301
 
265
- test('my test', async ({ page, switchScenario, scenaristTestId }) => {
302
+ test("my test", async ({ page, switchScenario, scenaristTestId }) => {
266
303
  // Your test code
267
304
  });
268
305
  ```
@@ -277,7 +314,7 @@ test('my test', async ({ page, switchScenario, scenaristTestId }) => {
277
314
  Re-exported from `@playwright/test` for convenience:
278
315
 
279
316
  ```typescript
280
- import { test, expect } from '@scenarist/playwright-helpers';
317
+ import { withScenarios, expect } from "@scenarist/playwright-helpers";
281
318
  ```
282
319
 
283
320
  #### Configuration Options
@@ -287,15 +324,41 @@ Set in `playwright.config.ts`:
287
324
  ```typescript
288
325
  export default defineConfig({
289
326
  use: {
290
- baseURL: 'http://localhost:3000', // Standard Playwright (used by switchScenario)
291
- scenaristEndpoint: '/api/__scenario__', // Scenarist endpoint path (default: '/api/__scenario__')
327
+ baseURL: "http://localhost:3000", // Standard Playwright (used by switchScenario)
328
+ scenaristEndpoint: "/api/__scenario__", // Scenarist endpoint path (default: '/api/__scenario__')
292
329
  },
293
330
  });
294
331
  ```
295
332
 
296
333
  **Available options:**
297
334
 
298
- - `scenaristEndpoint?: string` - The endpoint path for scenario switching (default: `'/api/__scenario__'`)
335
+ - `scenaristEndpoint?: string` - The endpoint path or absolute URL for scenario switching (default: `'/api/__scenario__'`)
336
+
337
+ ### Cross-Origin API Servers
338
+
339
+ When your API server runs on a different host or port than your frontend, use an **absolute URL** for `scenaristEndpoint`:
340
+
341
+ ```typescript
342
+ // Frontend: http://localhost:3000
343
+ // API Server: http://localhost:9090
344
+ export default defineConfig<ScenaristOptions>({
345
+ use: {
346
+ baseURL: "http://localhost:3000", // Frontend URL (for Playwright navigation)
347
+ scenaristEndpoint: "http://localhost:9090/__scenario__", // Absolute URL to API
348
+ },
349
+ });
350
+ ```
351
+
352
+ **How it works:**
353
+
354
+ - **Relative paths** (e.g., `/api/__scenario__`) are prepended with `baseURL`
355
+ - **Absolute URLs** (starting with `http://` or `https://`) are used directly, ignoring `baseURL`
356
+
357
+ This is useful when:
358
+
359
+ - Your API and frontend are separate services on different ports
360
+ - You're testing against a staging/production API endpoint
361
+ - Your test infrastructure uses a separate mock server
299
362
 
300
363
  #### `switchScenario` (Fixture)
301
364
 
@@ -327,16 +390,17 @@ await switchScenario(page, scenarioId, options?)
327
390
  For manual test ID control:
328
391
 
329
392
  ```typescript
330
- import { switchScenario } from '@scenarist/playwright-helpers';
393
+ import { switchScenario } from "@scenarist/playwright-helpers";
331
394
 
332
395
  await switchScenario(page, scenarioId, {
333
- baseURL: 'http://localhost:3000',
334
- endpoint: '/api/__scenario__',
335
- testId: 'my-custom-test-id', // Manual test ID
396
+ baseURL: "http://localhost:3000",
397
+ endpoint: "/api/__scenario__",
398
+ testId: "my-custom-test-id", // Manual test ID
336
399
  });
337
400
  ```
338
401
 
339
402
  **Use this only when:**
403
+
340
404
  - You need to share test IDs across multiple tests
341
405
  - You're integrating with existing test infrastructure that provides test IDs
342
406
  - You can't use Playwright fixtures for some reason
@@ -348,21 +412,24 @@ await switchScenario(page, scenarioId, {
348
412
  ### ❌ Don't: Switch scenarios after navigation
349
413
 
350
414
  ```typescript
351
- import { test } from '@scenarist/playwright-helpers';
415
+ import { test, expect } from "./fixtures"; // Import from YOUR fixtures file
352
416
 
353
- test('bad example', async ({ page, switchScenario }) => {
354
- await page.goto('/'); // BAD - Navigating first
355
- await switchScenario(page, 'premium'); // Headers set too late!
417
+ test("bad example", async ({ page, switchScenario }) => {
418
+ await page.goto("/"); // BAD - Navigating first
419
+ await switchScenario(page, "premium"); // Headers set too late!
356
420
  });
357
421
  ```
358
422
 
359
423
  **Why it fails**: Headers set AFTER navigation don't affect the already-loaded page.
360
424
 
361
425
  **Solution**: ✅ Switch scenario BEFORE navigating:
426
+
362
427
  ```typescript
363
- test('good example', async ({ page, switchScenario }) => {
364
- await switchScenario(page, 'premium'); // Set headers first
365
- await page.goto('/'); // Now requests use test ID header
428
+ import { test, expect } from "./fixtures";
429
+
430
+ test("good example", async ({ page, switchScenario }) => {
431
+ await switchScenario(page, "premium"); // Set headers first
432
+ await page.goto("/"); // Now requests use test ID header
366
433
  });
367
434
  ```
368
435
 
@@ -382,11 +449,12 @@ export default defineConfig({
382
449
  **Error**: `switchScenario` won't know where to send requests.
383
450
 
384
451
  **Solution**: ✅ Configure in `playwright.config.ts`:
452
+
385
453
  ```typescript
386
454
  export default defineConfig({
387
455
  use: {
388
- baseURL: 'http://localhost:3000',
389
- scenaristEndpoint: '/api/__scenario__',
456
+ baseURL: "http://localhost:3000",
457
+ scenaristEndpoint: "/api/__scenario__",
390
458
  },
391
459
  });
392
460
  ```
@@ -396,14 +464,14 @@ export default defineConfig({
396
464
  ### ❌ Don't: Use standalone `switchScenario` with manual test IDs
397
465
 
398
466
  ```typescript
399
- import { switchScenario } from '@scenarist/playwright-helpers';
467
+ import { switchScenario } from "@scenarist/playwright-helpers";
400
468
 
401
- test('bad example', async ({ page }) => {
469
+ test("bad example", async ({ page }) => {
402
470
  // BAD - Manual test ID risks conflicts
403
- await switchScenario(page, 'premium', {
404
- baseURL: 'http://localhost:3000',
405
- endpoint: '/api/__scenario__',
406
- testId: 'my-test', // Same ID across parallel tests = collision!
471
+ await switchScenario(page, "premium", {
472
+ baseURL: "http://localhost:3000",
473
+ endpoint: "/api/__scenario__",
474
+ testId: "my-test", // Same ID across parallel tests = collision!
407
475
  });
408
476
  });
409
477
  ```
@@ -411,11 +479,12 @@ test('bad example', async ({ page }) => {
411
479
  **Why it fails**: Multiple tests with the same ID will interfere with each other in parallel execution.
412
480
 
413
481
  **Solution**: ✅ Use the fixture API (auto-generates unique IDs):
482
+
414
483
  ```typescript
415
- import { test } from '@scenarist/playwright-helpers';
484
+ import { test, expect } from "./fixtures"; // Import from YOUR fixtures file
416
485
 
417
- test('good example', async ({ page, switchScenario }) => {
418
- await switchScenario(page, 'premium');
486
+ test("good example", async ({ page, switchScenario }) => {
487
+ await switchScenario(page, "premium");
419
488
  // Generates unique ID automatically: test-abc123-{uuid}
420
489
  });
421
490
  ```
@@ -427,6 +496,7 @@ test('good example', async ({ page, switchScenario }) => {
427
496
  **Answer**: We use a **two-layer approach** that tests different concerns:
428
497
 
429
498
  **Why this matters**:
499
+
430
500
  - ⚡ Fast feedback (1.7s vs 2-3s for full E2E)
431
501
  - 🎯 Pinpoint issues in Playwright integration vs framework integration
432
502
  - 📋 Comprehensive edge case coverage (13 test scenarios)
@@ -439,6 +509,7 @@ This package uses **real Playwright integration** in tests, which is an **except
439
509
  **⚠️ This is NOT the standard approach.** Most adapters (Express, Next.js, etc.) should mock external dependencies for fast, focused tests.
440
510
 
441
511
  **Why this package qualifies for exception** (per [ADR-0006](../../docs/adrs/0006-thin-adapters-real-integration-tests.md)):
512
+
442
513
  - ✅ Extremely thin (~40 lines)
443
514
  - ✅ Direct API wrappers only (no transformation)
444
515
  - ✅ Stable API (Playwright)
@@ -456,11 +527,13 @@ This package uses a **two-layer testing approach**:
456
527
  These tests validate the helper works correctly with **real Playwright** using MSW Node server. They prove the helper integrates with Playwright's Page API correctly.
457
528
 
458
529
  **Testing Stack**:
530
+
459
531
  - ✅ **Real Playwright** - Uses actual `@playwright/test` with real Page objects
460
532
  - ✅ **MSW Node Server** - Real HTTP server responding to requests
461
533
  - ✅ **No framework dependencies** - Tests helper + Playwright only
462
534
 
463
535
  **What We Test**:
536
+
464
537
  - ✅ Scenario switching succeeds with correct inputs
465
538
  - ✅ Test ID generation format and uniqueness
466
539
  - ✅ Endpoint URL construction (baseURL + endpoint)
@@ -473,17 +546,21 @@ These tests validate the helper works correctly with **real Playwright** using M
473
546
  **Value**: Tests helper's integration with Playwright in isolation. No Next.js, no MSW client, no complex stack - just helper + Playwright + HTTP server.
474
547
 
475
548
  **Example Test**:
549
+
476
550
  ```typescript
477
- test('should throw error when scenario switch fails with 404', async ({ page }) => {
551
+ test("should throw error when scenario switch fails with 404", async ({
552
+ page,
553
+ }) => {
478
554
  await expect(
479
- switchScenario(page, 'error-404', {
480
- baseURL: 'http://localhost:9876',
481
- })
555
+ switchScenario(page, "error-404", {
556
+ baseURL: "http://localhost:9876",
557
+ }),
482
558
  ).rejects.toThrow(/Failed to switch scenario: 404/);
483
559
  });
484
560
  ```
485
561
 
486
562
  **Run Package Tests**:
563
+
487
564
  ```bash
488
565
  cd packages/playwright-helpers
489
566
  pnpm test # Run all tests
@@ -497,6 +574,7 @@ pnpm test:watch # Interactive UI mode
497
574
  These tests validate the **complete integration** of helpers with real frameworks, real browsers, and real scenario endpoints.
498
575
 
499
576
  **What Integration Tests Cover**:
577
+
500
578
  - ✅ Helper works with real Playwright browsers (Chromium/Firefox/WebKit)
501
579
  - ✅ Helper works with real Next.js API routes
502
580
  - ✅ Helper works with real Scenarist scenario switching
@@ -505,18 +583,19 @@ These tests validate the **complete integration** of helpers with real framework
505
583
 
506
584
  **Why Both Layers Matter**:
507
585
 
508
- | Concern | Package Tests ✅ | Integration Tests ✅ |
509
- |---------|------------------|----------------------|
510
- | **Speed** | ⚡ Fast (1.7s) | 🐌 Slower (2-3s) |
511
- | **Scope** | Helper + Playwright only | Full stack (Next.js + MSW + Scenarist) |
512
- | **Debugging** | 🎯 Pinpoint Playwright integration issues | 🔍 Find framework integration issues |
513
- | **Coverage** | Edge cases + error handling | Happy paths + real scenarios |
514
- | **Dependencies** | Minimal (Playwright, MSW) | Many (Next.js, MSW client, Scenarist) |
515
- | **What it proves** | Helper works with Playwright API | Helper works with real frameworks |
586
+ | Concern | Package Tests ✅ | Integration Tests ✅ |
587
+ | ------------------ | ----------------------------------------- | -------------------------------------- |
588
+ | **Speed** | ⚡ Fast (1.7s) | 🐌 Slower (2-3s) |
589
+ | **Scope** | Helper + Playwright only | Full stack (Next.js + MSW + Scenarist) |
590
+ | **Debugging** | 🎯 Pinpoint Playwright integration issues | 🔍 Find framework integration issues |
591
+ | **Coverage** | Edge cases + error handling | Happy paths + real scenarios |
592
+ | **Dependencies** | Minimal (Playwright, MSW) | Many (Next.js, MSW client, Scenarist) |
593
+ | **What it proves** | Helper works with Playwright API | Helper works with real frameworks |
516
594
 
517
595
  **Takeaway**: Package tests prove Playwright integration. Integration tests prove framework integration.
518
596
 
519
597
  **Run Integration Tests**:
598
+
520
599
  ```bash
521
600
  # From repository root
522
601
  pnpm --filter=@scenarist/nextjs-pages-router-example test:e2e
@@ -529,15 +608,18 @@ pnpm --filter=@scenarist/nextjs-pages-router-example test:e2e
529
608
  **Answer**: This follows strict TDD with **deliberate refactoring**:
530
609
 
531
610
  **Phase 1a (RED)**: E2E test written first
611
+
532
612
  - ❌ Test fails: "switchScenario is not a function"
533
613
  - **This is the failing test that drove development**
534
614
 
535
615
  **Phase 1b (GREEN)**: Minimum implementation
616
+
536
617
  - ✅ Helper implementation created
537
618
  - ✅ E2E test passes
538
619
  - **Working code, ready to commit**
539
620
 
540
621
  **Phase 1c (REFACTOR)**: Edge case coverage added
622
+
541
623
  - 🔧 17 behavior tests added (error handling, edge cases, defaults)
542
624
  - ✅ All tests green, 100% coverage achieved
543
625
  - **Refactoring step per RED-GREEN-REFACTOR cycle**
@@ -550,14 +632,15 @@ This is textbook TDD: **RED** (E2E fails) → **GREEN** (implementation) → **R
550
632
 
551
633
  Our testing guidelines (from `docs/testing-guidelines.md`) require:
552
634
 
553
- | Guideline | How Package Tests Comply |
554
- |-----------|--------------------------|
555
- | **"Test through public API exclusively"** | ✅ Tests call `switchScenario()` only - internals invisible |
556
- | **"No 1:1 mapping between test/implementation files"** | ✅ Single test file, single public function, multiple behaviors |
557
- | **"Tests must document expected business behaviour"** | ✅ Each test describes observable behavior (error, headers, defaults) |
558
- | **"Behavior-driven - treat as black box"** | ✅ Tests verify inputs → outputs, implementation is opaque |
635
+ | Guideline | How Package Tests Comply |
636
+ | ------------------------------------------------------ | --------------------------------------------------------------------- |
637
+ | **"Test through public API exclusively"** | ✅ Tests call `switchScenario()` only - internals invisible |
638
+ | **"No 1:1 mapping between test/implementation files"** | ✅ Single test file, single public function, multiple behaviors |
639
+ | **"Tests must document expected business behaviour"** | ✅ Each test describes observable behavior (error, headers, defaults) |
640
+ | **"Behavior-driven - treat as black box"** | ✅ Tests verify inputs → outputs, implementation is opaque |
559
641
 
560
642
  **Key Distinction**:
643
+
561
644
  - ❌ **Unit testing** = Testing internal functions, mocking own code, coupling to implementation
562
645
  - ✅ **Behavior testing** = Testing public API, mocking external dependencies, verifying outcomes
563
646
 
@@ -92,9 +92,9 @@
92
92
  * For complete documentation, see the README at:
93
93
  * https://github.com/citypaul/scenarist/tree/main/packages/playwright-helpers
94
94
  */
95
- import { type Page } from '@playwright/test';
96
- import { type SwitchScenarioOptions } from './switch-scenario.js';
97
- import type { ScenaristScenarios, ScenarioIds } from '@scenarist/core';
95
+ import { type Page } from "@playwright/test";
96
+ import { type SwitchScenarioOptions } from "./switch-scenario.js";
97
+ import type { ScenaristScenarios, ScenarioIds } from "@scenarist/core";
98
98
  /**
99
99
  * Configuration options for Scenarist.
100
100
  *
@@ -160,7 +160,7 @@ export type ScenaristFixtures<S extends string = string> = {
160
160
  * });
161
161
  * ```
162
162
  */
163
- switchScenario: (page: Page, scenarioId: S, options?: Partial<Pick<SwitchScenarioOptions, 'endpoint' | 'baseURL'>>) => Promise<string>;
163
+ switchScenario: (page: Page, scenarioId: S, options?: Partial<Pick<SwitchScenarioOptions, "endpoint" | "baseURL">>) => Promise<string>;
164
164
  };
165
165
  /**
166
166
  * Create a type-safe Playwright test object with Scenarist fixtures.
@@ -1 +1 @@
1
- {"version":3,"file":"fixtures.d.ts","sourceRoot":"","sources":["../src/fixtures.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6FG;AAEH,OAAO,EAAsC,KAAK,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACjF,OAAO,EAAwC,KAAK,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AACxG,OAAO,KAAK,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEvE;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B;;;;;;;;;;;;;OAaG;IACH,iBAAiB,EAAE,MAAM,CAAC;CAC3B,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,iBAAiB,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,IAAI;IACzD;;;;;;;OAOG;IACH,eAAe,EAAE,MAAM,CAAC;IAExB;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;IACH,cAAc,EAAE,CACd,IAAI,EAAE,IAAI,EACV,UAAU,EAAE,CAAC,EACb,OAAO,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,qBAAqB,EAAE,UAAU,GAAG,SAAS,CAAC,CAAC,KACnE,OAAO,CAAC,MAAM,CAAC,CAAC;CACtB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,aAAa,CAAC,CAAC,SAAS,kBAAkB,EAAE,SAAS,EAAE,CAAC,sSAwCvE;AAED,eAAO,MAAM,MAAM,uCAAa,CAAC"}
1
+ {"version":3,"file":"fixtures.d.ts","sourceRoot":"","sources":["../src/fixtures.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6FG;AAEH,OAAO,EAGL,KAAK,IAAI,EACV,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAEL,KAAK,qBAAqB,EAC3B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEvE;;;;GAIG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B;;;;;;;;;;;;;OAaG;IACH,iBAAiB,EAAE,MAAM,CAAC;CAC3B,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,iBAAiB,CAAC,CAAC,SAAS,MAAM,GAAG,MAAM,IAAI;IACzD;;;;;;;OAOG;IACH,eAAe,EAAE,MAAM,CAAC;IAExB;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;IACH,cAAc,EAAE,CACd,IAAI,EAAE,IAAI,EACV,UAAU,EAAE,CAAC,EACb,OAAO,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,qBAAqB,EAAE,UAAU,GAAG,SAAS,CAAC,CAAC,KACnE,OAAO,CAAC,MAAM,CAAC,CAAC;CACtB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,aAAa,CAAC,CAAC,SAAS,kBAAkB,EAAE,SAAS,EAAE,CAAC,sSA4CvE;AAED,eAAO,MAAM,MAAM,uCAAa,CAAC"}
package/dist/fixtures.js CHANGED
@@ -92,8 +92,8 @@
92
92
  * For complete documentation, see the README at:
93
93
  * https://github.com/citypaul/scenarist/tree/main/packages/playwright-helpers
94
94
  */
95
- import { test as base, expect as baseExpect } from '@playwright/test';
96
- import { switchScenario as baseSwitchScenario } from './switch-scenario.js';
95
+ import { test as base, expect as baseExpect, } from "@playwright/test";
96
+ import { switchScenario as baseSwitchScenario, } from "./switch-scenario.js";
97
97
  /**
98
98
  * Create a type-safe Playwright test object with Scenarist fixtures.
99
99
  *
@@ -131,7 +131,7 @@ export function withScenarios(scenarios) {
131
131
  void scenarios;
132
132
  return base.extend({
133
133
  // Configuration option with default value
134
- scenaristEndpoint: ['/api/__scenario__', { option: true }],
134
+ scenaristEndpoint: ["/api/__scenario__", { option: true }],
135
135
  // Generate a guaranteed unique test ID for each test
136
136
  scenaristTestId: async ({}, use, testInfo) => {
137
137
  // Use test info + UUID for guaranteed uniqueness
@@ -143,7 +143,7 @@ export function withScenarios(scenarios) {
143
143
  const switchFn = async (page, scenarioId, options) => {
144
144
  // Read from config, allow per-test override, fallback to defaults
145
145
  const finalEndpoint = options?.endpoint ?? scenaristEndpoint;
146
- const finalBaseURL = options?.baseURL ?? baseURL ?? 'http://localhost:3000';
146
+ const finalBaseURL = options?.baseURL ?? baseURL ?? "http://localhost:3000";
147
147
  // Call the base switchScenario with all config and return test ID
148
148
  return await baseSwitchScenario(page, scenarioId, {
149
149
  endpoint: finalEndpoint,
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { switchScenario, type SwitchScenarioOptions } from './switch-scenario.js';
2
- export { withScenarios, expect, type ScenaristOptions, type ScenaristFixtures } from './fixtures.js';
3
- export { SCENARIST_TEST_ID_HEADER } from '@scenarist/core';
1
+ export { switchScenario, type SwitchScenarioOptions, } from "./switch-scenario.js";
2
+ export { withScenarios, expect, type ScenaristOptions, type ScenaristFixtures, } from "./fixtures.js";
3
+ export { SCENARIST_TEST_ID_HEADER } from "@scenarist/core";
4
4
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,KAAK,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AAClF,OAAO,EAAE,aAAa,EAAE,MAAM,EAAE,KAAK,gBAAgB,EAAE,KAAK,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAErG,OAAO,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,KAAK,qBAAqB,GAC3B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,aAAa,EACb,MAAM,EACN,KAAK,gBAAgB,EACrB,KAAK,iBAAiB,GACvB,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC"}
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { switchScenario } from './switch-scenario.js';
2
- export { withScenarios, expect } from './fixtures.js';
1
+ export { switchScenario, } from "./switch-scenario.js";
2
+ export { withScenarios, expect, } from "./fixtures.js";
3
3
  // Re-export header constant for user convenience
4
- export { SCENARIST_TEST_ID_HEADER } from '@scenarist/core';
4
+ export { SCENARIST_TEST_ID_HEADER } from "@scenarist/core";
@@ -1,4 +1,4 @@
1
- import type { Page } from '@playwright/test';
1
+ import type { Page } from "@playwright/test";
2
2
  /**
3
3
  * Options for switchScenario helper
4
4
  */
@@ -1 +1 @@
1
- {"version":3,"file":"switch-scenario.d.ts","sourceRoot":"","sources":["../src/switch-scenario.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAG7C;;GAEG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC;;;OAGG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAEzB;;;OAGG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAE3B;;;;OAIG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AA8BF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,eAAO,MAAM,cAAc,GACzB,MAAM,IAAI,EACV,YAAY,MAAM,EAClB,SAAS,qBAAqB,KAC7B,OAAO,CAAC,MAAM,CAmChB,CAAC"}
1
+ {"version":3,"file":"switch-scenario.d.ts","sourceRoot":"","sources":["../src/switch-scenario.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAG7C;;GAEG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC;;;OAGG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAEzB;;;OAGG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAE3B;;;;OAIG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AA8BF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,eAAO,MAAM,cAAc,GACzB,MAAM,IAAI,EACV,YAAY,MAAM,EAClB,SAAS,qBAAqB,KAC7B,OAAO,CAAC,MAAM,CAsChB,CAAC"}
@@ -1,4 +1,4 @@
1
- import { SCENARIST_TEST_ID_HEADER } from '@scenarist/core';
1
+ import { SCENARIST_TEST_ID_HEADER } from "@scenarist/core";
2
2
  /**
3
3
  * Establish route interception and header injection for test ID propagation.
4
4
  *
@@ -11,9 +11,9 @@ import { SCENARIST_TEST_ID_HEADER } from '@scenarist/core';
11
11
  */
12
12
  const establishTestIdInterception = async (page, testId) => {
13
13
  // Clear any existing handlers to prevent accumulation
14
- await page.unroute('**/*');
14
+ await page.unroute("**/*");
15
15
  // Intercept all routes to inject test ID header
16
- await page.route('**/*', async (route) => {
16
+ await page.route("**/*", async (route) => {
17
17
  const headers = route.request().headers();
18
18
  headers[SCENARIST_TEST_ID_HEADER] = testId;
19
19
  await route.continue({ headers });
@@ -54,7 +54,7 @@ const establishTestIdInterception = async (page, testId) => {
54
54
  * ```
55
55
  */
56
56
  export const switchScenario = async (page, scenarioId, options) => {
57
- const { baseURL, endpoint = '/__scenario__', testId: providedTestId, } = options;
57
+ const { baseURL, endpoint = "/__scenario__", testId: providedTestId, } = options;
58
58
  // Use provided test ID (from fixture) or generate unique one
59
59
  // When using fixtures, test ID is guaranteed unique by Playwright's test context
60
60
  // Date.now() can collide when tests run in parallel within the same millisecond
@@ -63,7 +63,9 @@ export const switchScenario = async (page, scenarioId, options) => {
63
63
  // Client Components may fire API calls immediately on mount/navigation
64
64
  await establishTestIdInterception(page, testId);
65
65
  // Call scenario endpoint
66
- const url = `${baseURL}${endpoint}`;
66
+ // Support absolute URLs for when API is on different host/port than frontend
67
+ const isAbsoluteUrl = endpoint.startsWith("http://") || endpoint.startsWith("https://");
68
+ const url = isAbsoluteUrl ? endpoint : `${baseURL}${endpoint}`;
67
69
  const response = await page.request.post(url, {
68
70
  headers: { [SCENARIST_TEST_ID_HEADER]: testId },
69
71
  data: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scenarist/playwright-helpers",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
4
4
  "description": "Playwright test helpers for Scenarist scenario management",
5
5
  "author": "Paul Hammond (citypaul) <paul@packsoftware.co.uk>",
6
6
  "license": "MIT",
@@ -29,10 +29,12 @@
29
29
  },
30
30
  "type": "module",
31
31
  "sideEffects": false,
32
+ "main": "./dist/index.js",
33
+ "types": "./dist/index.d.ts",
32
34
  "exports": {
33
35
  ".": {
34
36
  "types": "./dist/index.d.ts",
35
- "import": "./dist/index.js"
37
+ "default": "./dist/index.js"
36
38
  }
37
39
  },
38
40
  "files": [