@scenarist/playwright-helpers 0.0.1 → 0.1.0
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/LICENSE +21 -0
- package/README.md +575 -27
- package/dist/fixtures.d.ts +198 -0
- package/dist/fixtures.d.ts.map +1 -0
- package/dist/fixtures.js +158 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/switch-scenario.d.ts +56 -0
- package/dist/switch-scenario.d.ts.map +1 -0
- package/dist/switch-scenario.js +80 -0
- package/dist/types.d.ts +8 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +7 -0
- package/dist/utils.d.ts +8 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +8 -0
- package/package.json +62 -7
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Paul Hammond (citypaul)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,45 +1,593 @@
|
|
|
1
1
|
# @scenarist/playwright-helpers
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@scenarist/playwright-helpers)
|
|
4
|
+
[](https://opensource.org/licenses/MIT)
|
|
4
5
|
|
|
5
|
-
|
|
6
|
+
Playwright test helpers for [Scenarist](https://scenarist.io) scenario management with guaranteed test isolation.
|
|
6
7
|
|
|
7
|
-
|
|
8
|
+
## Installation
|
|
8
9
|
|
|
9
|
-
|
|
10
|
+
```bash
|
|
11
|
+
# npm
|
|
12
|
+
npm install -D @scenarist/playwright-helpers
|
|
10
13
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
2. Enable secure, token-less publishing from CI/CD workflows
|
|
14
|
-
3. Establish provenance for packages published under this name
|
|
14
|
+
# pnpm
|
|
15
|
+
pnpm add -D @scenarist/playwright-helpers
|
|
15
16
|
|
|
16
|
-
|
|
17
|
+
# yarn
|
|
18
|
+
yarn add -D @scenarist/playwright-helpers
|
|
19
|
+
```
|
|
17
20
|
|
|
18
|
-
|
|
21
|
+
## Quick Start (Recommended: Fixtures API)
|
|
19
22
|
|
|
20
|
-
|
|
23
|
+
The **fixtures API** is the recommended way to use Scenarist with Playwright. It provides:
|
|
24
|
+
- ✅ Guaranteed unique test IDs (no collisions, even with parallel execution)
|
|
25
|
+
- ✅ Configuration in one place (no repetition across tests)
|
|
26
|
+
- ✅ Clean composition with your existing fixtures
|
|
27
|
+
- ✅ Type-safe with full TypeScript support
|
|
21
28
|
|
|
22
|
-
|
|
29
|
+
### 1. Configure in `playwright.config.ts`
|
|
23
30
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
4. Use the configured workflow to publish your actual package
|
|
31
|
+
```typescript
|
|
32
|
+
import { defineConfig } from '@playwright/test';
|
|
33
|
+
import type { ScenaristOptions } from '@scenarist/playwright-helpers';
|
|
28
34
|
|
|
29
|
-
|
|
35
|
+
export default defineConfig<ScenaristOptions>({
|
|
36
|
+
use: {
|
|
37
|
+
baseURL: 'http://localhost:3000', // Standard Playwright config
|
|
38
|
+
scenaristEndpoint: '/api/__scenario__', // Scenarist-specific config
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
```
|
|
30
42
|
|
|
31
|
-
|
|
32
|
-
- Contains no executable code
|
|
33
|
-
- Provides no functionality
|
|
34
|
-
- Should not be installed as a dependency
|
|
35
|
-
- Exists only for administrative purposes
|
|
43
|
+
**Note:** The `<ScenaristOptions>` type parameter enables TypeScript to recognize `scenaristEndpoint` as a valid configuration option.
|
|
36
44
|
|
|
37
|
-
|
|
45
|
+
### 2. Use in Tests
|
|
38
46
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
47
|
+
```typescript
|
|
48
|
+
import { test, expect } from '@scenarist/playwright-helpers';
|
|
49
|
+
|
|
50
|
+
test('premium user sees premium pricing', async ({ page, switchScenario }) => {
|
|
51
|
+
// Configuration read from playwright.config.ts - no repetition!
|
|
52
|
+
await switchScenario(page, 'premiumUser');
|
|
53
|
+
|
|
54
|
+
await page.goto('/');
|
|
55
|
+
await expect(page.getByRole('heading', { name: 'Premium' })).toBeVisible();
|
|
56
|
+
});
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
That's it! No manual test ID generation, no repeating baseURL/endpoint, guaranteed test isolation.
|
|
60
|
+
|
|
61
|
+
## Composing with Your Existing Fixtures
|
|
62
|
+
|
|
63
|
+
If your team already has custom Playwright fixtures, you can easily compose them with Scenarist fixtures:
|
|
64
|
+
|
|
65
|
+
```typescript
|
|
66
|
+
// tests/fixtures.ts
|
|
67
|
+
import { test as scenaristTest } from '@scenarist/playwright-helpers';
|
|
68
|
+
|
|
69
|
+
type MyFixtures = {
|
|
70
|
+
authenticatedPage: Page;
|
|
71
|
+
database: Database;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
export const test = scenaristTest.extend<MyFixtures>({
|
|
75
|
+
authenticatedPage: async ({ page }, use) => {
|
|
76
|
+
// Your custom fixture logic
|
|
77
|
+
await page.goto('/login');
|
|
78
|
+
await page.fill('[name=email]', 'test@example.com');
|
|
79
|
+
await page.fill('[name=password]', 'password');
|
|
80
|
+
await page.click('button[type=submit]');
|
|
81
|
+
await use(page);
|
|
82
|
+
},
|
|
83
|
+
|
|
84
|
+
database: async ({}, use) => {
|
|
85
|
+
const db = await connectToTestDatabase();
|
|
86
|
+
await use(db);
|
|
87
|
+
await db.close();
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
export { expect } from '@scenarist/playwright-helpers';
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Now use your extended test object:
|
|
95
|
+
|
|
96
|
+
```typescript
|
|
97
|
+
// tests/my-test.spec.ts
|
|
98
|
+
import { test, expect } from './fixtures';
|
|
99
|
+
|
|
100
|
+
test('authenticated premium user flow', async ({ authenticatedPage, switchScenario, database }) => {
|
|
101
|
+
// All fixtures available: yours + Scenarist's
|
|
102
|
+
await switchScenario(authenticatedPage, 'premiumUser');
|
|
103
|
+
await authenticatedPage.goto('/dashboard');
|
|
104
|
+
|
|
105
|
+
const user = await database.getUser('test@example.com');
|
|
106
|
+
expect(user.tier).toBe('premium');
|
|
107
|
+
});
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Type-Safe Scenario IDs (Optional but Recommended)
|
|
111
|
+
|
|
112
|
+
Get autocomplete and type checking for scenario names:
|
|
113
|
+
|
|
114
|
+
### 1. Define Scenarios with Type Export
|
|
115
|
+
|
|
116
|
+
```typescript
|
|
117
|
+
// lib/scenarios.ts
|
|
118
|
+
import type { ScenaristScenario, ScenaristScenarios } from '@scenarist/core';
|
|
119
|
+
|
|
120
|
+
export const scenarios = {
|
|
121
|
+
cartWithState: { id: 'cartWithState', name: 'Cart with State', ... },
|
|
122
|
+
premiumUser: { id: 'premiumUser', name: 'Premium User', ... },
|
|
123
|
+
standardUser: { id: 'standardUser', name: 'Standard User', ... },
|
|
124
|
+
} as const satisfies ScenaristScenarios;
|
|
125
|
+
|
|
126
|
+
// Derive type from actual scenarios (or use ScenarioIds<typeof scenarios>)
|
|
127
|
+
export type ScenarioId = keyof typeof scenarios;
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
### 2. Create Typed Test Object
|
|
131
|
+
|
|
132
|
+
```typescript
|
|
133
|
+
// tests/fixtures.ts
|
|
134
|
+
import { createTest, expect } from '@scenarist/playwright-helpers';
|
|
135
|
+
import type { ScenarioId } from '../lib/scenarios';
|
|
136
|
+
|
|
137
|
+
// Create typed test object with your scenario IDs
|
|
138
|
+
export const test = createTest<ScenarioId>();
|
|
139
|
+
export { expect };
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
### 3. Use with Full Autocomplete
|
|
143
|
+
|
|
144
|
+
```typescript
|
|
145
|
+
// tests/my-test.spec.ts
|
|
146
|
+
import { test, expect } from './fixtures';
|
|
147
|
+
|
|
148
|
+
test('my test', async ({ page, switchScenario }) => {
|
|
149
|
+
await switchScenario(page, 'cart'); // ❌ TypeScript error: not a valid scenario
|
|
150
|
+
await switchScenario(page, 'cartWithState'); // ✅ Autocomplete works!
|
|
151
|
+
// ^
|
|
152
|
+
// Autocomplete shows all valid scenario IDs
|
|
153
|
+
});
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
**Benefits:**
|
|
157
|
+
- ✅ Autocomplete shows all valid scenario names
|
|
158
|
+
- ✅ TypeScript errors for typos or invalid scenarios
|
|
159
|
+
- ✅ Type stays in sync with actual scenarios (single source of truth)
|
|
160
|
+
- ✅ Works seamlessly with fixture composition
|
|
161
|
+
|
|
162
|
+
## Advanced: Per-Test Configuration Overrides
|
|
163
|
+
|
|
164
|
+
Most tests use the global config, but you can override for specific tests:
|
|
165
|
+
|
|
166
|
+
```typescript
|
|
167
|
+
test('staging environment test', async ({ page, switchScenario }) => {
|
|
168
|
+
await switchScenario(page, 'myScenario', {
|
|
169
|
+
baseURL: 'https://staging.example.com', // Override for this test only
|
|
170
|
+
endpoint: '/api/custom-endpoint',
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
await page.goto('/');
|
|
174
|
+
// Test against staging environment
|
|
175
|
+
});
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
## Advanced: Standalone `switchScenario` Function
|
|
179
|
+
|
|
180
|
+
For cases where you need manual control over test IDs or can't use fixtures:
|
|
181
|
+
|
|
182
|
+
```typescript
|
|
183
|
+
import { test, expect } from '@playwright/test';
|
|
184
|
+
import { switchScenario } from '@scenarist/playwright-helpers';
|
|
185
|
+
|
|
186
|
+
test('premium user scenario', async ({ page }) => {
|
|
187
|
+
// Switch to premium scenario (generates unique test ID, sets headers automatically)
|
|
188
|
+
await switchScenario(page, 'premiumUser', {
|
|
189
|
+
baseURL: 'http://localhost:3000',
|
|
190
|
+
endpoint: '/api/__scenario__',
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
// Navigate and test as premium user
|
|
194
|
+
await page.goto('/');
|
|
195
|
+
await expect(page.locator('.premium-badge')).toBeVisible();
|
|
196
|
+
});
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
> **Note on testing**: This package has comprehensive behavior-driven tests at the package level. This is NOT unit testing - we test observable behavior through the public API only. See [Testing Philosophy](#testing-philosophy) below for full rationale.
|
|
200
|
+
|
|
201
|
+
#### Options
|
|
202
|
+
|
|
203
|
+
```typescript
|
|
204
|
+
type SwitchScenarioOptions = {
|
|
205
|
+
readonly baseURL: string; // Base URL of your application
|
|
206
|
+
readonly endpoint?: string; // Scenario endpoint path (default: '/__scenario__')
|
|
207
|
+
readonly testIdHeader?: string; // Test ID header name (default: 'x-scenarist-test-id')
|
|
208
|
+
readonly variant?: string; // Optional scenario variant
|
|
209
|
+
};
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
#### What it does
|
|
213
|
+
|
|
214
|
+
The `switchScenario` helper:
|
|
215
|
+
1. Generates a unique test ID (`test-{scenarioId}-{timestamp}`)
|
|
216
|
+
2. POSTs to the scenario endpoint with the test ID header
|
|
217
|
+
3. Verifies the scenario switch succeeded (200 response)
|
|
218
|
+
4. Sets the test ID header for all subsequent requests in the test
|
|
219
|
+
|
|
220
|
+
This reduces scenario switching from 9 lines of boilerplate to 2 lines:
|
|
221
|
+
|
|
222
|
+
**Without helper (9 lines):**
|
|
223
|
+
```typescript
|
|
224
|
+
const testId = `test-premium-${Date.now()}`;
|
|
225
|
+
const response = await page.request.post('http://localhost:3000/api/__scenario__', {
|
|
226
|
+
headers: { 'x-scenarist-test-id': testId },
|
|
227
|
+
data: { scenario: 'premiumUser' },
|
|
228
|
+
});
|
|
229
|
+
expect(response.status()).toBe(200);
|
|
230
|
+
await page.setExtraHTTPHeaders({ 'x-scenarist-test-id': testId });
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
**With helper (2 lines):**
|
|
234
|
+
```typescript
|
|
235
|
+
await switchScenario(page, 'premiumUser', {
|
|
236
|
+
baseURL: 'http://localhost:3000',
|
|
237
|
+
endpoint: '/api/__scenario__',
|
|
238
|
+
});
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
**Code reduction: 77%**
|
|
242
|
+
|
|
243
|
+
## API Reference
|
|
244
|
+
|
|
245
|
+
### Fixtures API (Recommended)
|
|
246
|
+
|
|
247
|
+
#### `test`
|
|
248
|
+
|
|
249
|
+
Extended Playwright test object with Scenarist fixtures.
|
|
250
|
+
|
|
251
|
+
```typescript
|
|
252
|
+
import { test } from '@scenarist/playwright-helpers';
|
|
253
|
+
|
|
254
|
+
test('my test', async ({ page, switchScenario, scenaristTestId }) => {
|
|
255
|
+
// Your test code
|
|
256
|
+
});
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
**Fixtures provided:**
|
|
260
|
+
|
|
261
|
+
- `switchScenario(page, scenarioId, options?)` - Switch to a scenario (auto-injects test ID)
|
|
262
|
+
- `scenaristTestId` - Unique test ID for this test (usually don't need to access directly)
|
|
263
|
+
|
|
264
|
+
#### `expect`
|
|
265
|
+
|
|
266
|
+
Re-exported from `@playwright/test` for convenience:
|
|
267
|
+
|
|
268
|
+
```typescript
|
|
269
|
+
import { test, expect } from '@scenarist/playwright-helpers';
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
#### Configuration Options
|
|
273
|
+
|
|
274
|
+
Set in `playwright.config.ts`:
|
|
275
|
+
|
|
276
|
+
```typescript
|
|
277
|
+
export default defineConfig({
|
|
278
|
+
use: {
|
|
279
|
+
baseURL: 'http://localhost:3000', // Standard Playwright (used by switchScenario)
|
|
280
|
+
scenaristEndpoint: '/api/__scenario__', // Scenarist endpoint path (default: '/api/__scenario__')
|
|
281
|
+
},
|
|
282
|
+
});
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
**Available options:**
|
|
286
|
+
|
|
287
|
+
- `scenaristEndpoint?: string` - The endpoint path for scenario switching (default: `'/api/__scenario__'`)
|
|
288
|
+
|
|
289
|
+
#### `switchScenario` (Fixture)
|
|
290
|
+
|
|
291
|
+
Switch to a scenario using the automatically generated test ID.
|
|
292
|
+
|
|
293
|
+
```typescript
|
|
294
|
+
await switchScenario(page, scenarioId, options?)
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
**Parameters:**
|
|
298
|
+
|
|
299
|
+
- `page: Page` - Playwright Page object
|
|
300
|
+
- `scenarioId: string` - The scenario to switch to
|
|
301
|
+
- `options?: { baseURL?: string; endpoint?: string }` - Optional overrides (rarely needed)
|
|
302
|
+
|
|
303
|
+
**What it does:**
|
|
304
|
+
|
|
305
|
+
1. Reads `baseURL` from Playwright config (or uses override)
|
|
306
|
+
2. Reads `scenaristEndpoint` from Playwright config (or uses override)
|
|
307
|
+
3. Generates unique test ID automatically (via `scenaristTestId` fixture)
|
|
308
|
+
4. POSTs to scenario endpoint with test ID header
|
|
309
|
+
5. Verifies scenario switch succeeded
|
|
310
|
+
6. Sets test ID header for all subsequent requests
|
|
311
|
+
|
|
312
|
+
### Standalone API (Advanced)
|
|
313
|
+
|
|
314
|
+
#### `switchScenario` (Function)
|
|
315
|
+
|
|
316
|
+
For manual test ID control:
|
|
317
|
+
|
|
318
|
+
```typescript
|
|
319
|
+
import { switchScenario } from '@scenarist/playwright-helpers';
|
|
320
|
+
|
|
321
|
+
await switchScenario(page, scenarioId, {
|
|
322
|
+
baseURL: 'http://localhost:3000',
|
|
323
|
+
endpoint: '/api/__scenario__',
|
|
324
|
+
testId: 'my-custom-test-id', // Manual test ID
|
|
325
|
+
});
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
**Use this only when:**
|
|
329
|
+
- You need to share test IDs across multiple tests
|
|
330
|
+
- You're integrating with existing test infrastructure that provides test IDs
|
|
331
|
+
- You can't use Playwright fixtures for some reason
|
|
332
|
+
|
|
333
|
+
**⚠️ Warning:** Manual test IDs can cause collisions in parallel execution. The fixture API is safer.
|
|
334
|
+
|
|
335
|
+
## Common Pitfalls
|
|
336
|
+
|
|
337
|
+
### ❌ Don't: Switch scenarios after navigation
|
|
338
|
+
|
|
339
|
+
```typescript
|
|
340
|
+
import { test } from '@scenarist/playwright-helpers';
|
|
341
|
+
|
|
342
|
+
test('bad example', async ({ page, switchScenario }) => {
|
|
343
|
+
await page.goto('/'); // BAD - Navigating first
|
|
344
|
+
await switchScenario(page, 'premium'); // Headers set too late!
|
|
345
|
+
});
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
**Why it fails**: Headers set AFTER navigation don't affect the already-loaded page.
|
|
349
|
+
|
|
350
|
+
**Solution**: ✅ Switch scenario BEFORE navigating:
|
|
351
|
+
```typescript
|
|
352
|
+
test('good example', async ({ page, switchScenario }) => {
|
|
353
|
+
await switchScenario(page, 'premium'); // Set headers first
|
|
354
|
+
await page.goto('/'); // Now requests use test ID header
|
|
355
|
+
});
|
|
356
|
+
```
|
|
42
357
|
|
|
43
358
|
---
|
|
44
359
|
|
|
45
|
-
|
|
360
|
+
### ❌ Don't: Forget to configure in playwright.config.ts
|
|
361
|
+
|
|
362
|
+
```typescript
|
|
363
|
+
// playwright.config.ts - Missing configuration!
|
|
364
|
+
export default defineConfig({
|
|
365
|
+
use: {
|
|
366
|
+
// Missing: baseURL and scenaristEndpoint
|
|
367
|
+
},
|
|
368
|
+
});
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
**Error**: `switchScenario` won't know where to send requests.
|
|
372
|
+
|
|
373
|
+
**Solution**: ✅ Configure in `playwright.config.ts`:
|
|
374
|
+
```typescript
|
|
375
|
+
export default defineConfig({
|
|
376
|
+
use: {
|
|
377
|
+
baseURL: 'http://localhost:3000',
|
|
378
|
+
scenaristEndpoint: '/api/__scenario__',
|
|
379
|
+
},
|
|
380
|
+
});
|
|
381
|
+
```
|
|
382
|
+
|
|
383
|
+
---
|
|
384
|
+
|
|
385
|
+
### ❌ Don't: Use standalone `switchScenario` with manual test IDs
|
|
386
|
+
|
|
387
|
+
```typescript
|
|
388
|
+
import { switchScenario } from '@scenarist/playwright-helpers';
|
|
389
|
+
|
|
390
|
+
test('bad example', async ({ page }) => {
|
|
391
|
+
// BAD - Manual test ID risks conflicts
|
|
392
|
+
await switchScenario(page, 'premium', {
|
|
393
|
+
baseURL: 'http://localhost:3000',
|
|
394
|
+
endpoint: '/api/__scenario__',
|
|
395
|
+
testId: 'my-test', // Same ID across parallel tests = collision!
|
|
396
|
+
});
|
|
397
|
+
});
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
**Why it fails**: Multiple tests with the same ID will interfere with each other in parallel execution.
|
|
401
|
+
|
|
402
|
+
**Solution**: ✅ Use the fixture API (auto-generates unique IDs):
|
|
403
|
+
```typescript
|
|
404
|
+
import { test } from '@scenarist/playwright-helpers';
|
|
405
|
+
|
|
406
|
+
test('good example', async ({ page, switchScenario }) => {
|
|
407
|
+
await switchScenario(page, 'premium');
|
|
408
|
+
// Generates unique ID automatically: test-abc123-{uuid}
|
|
409
|
+
});
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
## Testing Philosophy
|
|
413
|
+
|
|
414
|
+
**You might be thinking**: "Why test the helpers in their own package when they're already tested in Next.js?"
|
|
415
|
+
|
|
416
|
+
**Answer**: We use a **two-layer approach** that tests different concerns:
|
|
417
|
+
|
|
418
|
+
**Why this matters**:
|
|
419
|
+
- ⚡ Fast feedback (1.7s vs 2-3s for full E2E)
|
|
420
|
+
- 🎯 Pinpoint issues in Playwright integration vs framework integration
|
|
421
|
+
- 📋 Comprehensive edge case coverage (13 test scenarios)
|
|
422
|
+
- 🔒 Tests prove helper works with real Playwright API
|
|
423
|
+
|
|
424
|
+
### Testing Strategy: Real Playwright Integration (Exception to Layer 2 Rule)
|
|
425
|
+
|
|
426
|
+
This package uses **real Playwright integration** in tests, which is an **exception** to the general adapter testing rule (ADR-0003 Layer 2 prescribes mocking external dependencies).
|
|
427
|
+
|
|
428
|
+
**⚠️ This is NOT the standard approach.** Most adapters (Express, Next.js, etc.) should mock external dependencies for fast, focused tests.
|
|
429
|
+
|
|
430
|
+
**Why this package qualifies for exception** (per [ADR-0006](../../docs/adrs/0006-thin-adapters-real-integration-tests.md)):
|
|
431
|
+
- ✅ Extremely thin (~40 lines)
|
|
432
|
+
- ✅ Direct API wrappers only (no transformation)
|
|
433
|
+
- ✅ Stable API (Playwright)
|
|
434
|
+
- ✅ Fast tests (1.7s)
|
|
435
|
+
- ✅ Real integration provides significantly higher confidence
|
|
436
|
+
|
|
437
|
+
See [ADR-0006](../../docs/adrs/0006-thin-adapters-real-integration-tests.md) for full decision criteria and when to use real dependencies vs. mocks.
|
|
438
|
+
|
|
439
|
+
This package uses a **two-layer testing approach**:
|
|
440
|
+
|
|
441
|
+
### Layer 1: Playwright Integration Tests (This Package)
|
|
442
|
+
|
|
443
|
+
**Location**: `packages/playwright-helpers/tests/`
|
|
444
|
+
|
|
445
|
+
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.
|
|
446
|
+
|
|
447
|
+
**Testing Stack**:
|
|
448
|
+
- ✅ **Real Playwright** - Uses actual `@playwright/test` with real Page objects
|
|
449
|
+
- ✅ **MSW Node Server** - Real HTTP server responding to requests
|
|
450
|
+
- ✅ **No framework dependencies** - Tests helper + Playwright only
|
|
451
|
+
|
|
452
|
+
**What We Test**:
|
|
453
|
+
- ✅ Scenario switching succeeds with correct inputs
|
|
454
|
+
- ✅ Test ID generation format and uniqueness
|
|
455
|
+
- ✅ Endpoint URL construction (baseURL + endpoint)
|
|
456
|
+
- ✅ Request body structure (scenario, variant)
|
|
457
|
+
- ✅ Custom header support (testIdHeader)
|
|
458
|
+
- ✅ Error handling (404, 400, 500 responses)
|
|
459
|
+
- ✅ Multiple concurrent scenarios work independently
|
|
460
|
+
- ✅ Default values for optional parameters
|
|
461
|
+
|
|
462
|
+
**Value**: Tests helper's integration with Playwright in isolation. No Next.js, no MSW client, no complex stack - just helper + Playwright + HTTP server.
|
|
463
|
+
|
|
464
|
+
**Example Test**:
|
|
465
|
+
```typescript
|
|
466
|
+
test('should throw error when scenario switch fails with 404', async ({ page }) => {
|
|
467
|
+
await expect(
|
|
468
|
+
switchScenario(page, 'error-404', {
|
|
469
|
+
baseURL: 'http://localhost:9876',
|
|
470
|
+
})
|
|
471
|
+
).rejects.toThrow(/Failed to switch scenario: 404/);
|
|
472
|
+
});
|
|
473
|
+
```
|
|
474
|
+
|
|
475
|
+
**Run Package Tests**:
|
|
476
|
+
```bash
|
|
477
|
+
cd packages/playwright-helpers
|
|
478
|
+
pnpm test # Run all tests
|
|
479
|
+
pnpm test:watch # Interactive UI mode
|
|
480
|
+
```
|
|
481
|
+
|
|
482
|
+
### Layer 2: Integration Tests (Next.js App)
|
|
483
|
+
|
|
484
|
+
**Location**: `apps/nextjs-pages-router-example/tests/playwright/scenario-switching.spec.ts`
|
|
485
|
+
|
|
486
|
+
These tests validate the **complete integration** of helpers with real frameworks, real browsers, and real scenario endpoints.
|
|
487
|
+
|
|
488
|
+
**What Integration Tests Cover**:
|
|
489
|
+
- ✅ Helper works with real Playwright browsers (Chromium/Firefox/WebKit)
|
|
490
|
+
- ✅ Helper works with real Next.js API routes
|
|
491
|
+
- ✅ Helper works with real Scenarist scenario switching
|
|
492
|
+
- ✅ Full user journey (switch → navigate → verify)
|
|
493
|
+
- ✅ Next.js-specific behavior (Pages Router conventions)
|
|
494
|
+
|
|
495
|
+
**Why Both Layers Matter**:
|
|
496
|
+
|
|
497
|
+
| Concern | Package Tests ✅ | Integration Tests ✅ |
|
|
498
|
+
|---------|------------------|----------------------|
|
|
499
|
+
| **Speed** | ⚡ Fast (1.7s) | 🐌 Slower (2-3s) |
|
|
500
|
+
| **Scope** | Helper + Playwright only | Full stack (Next.js + MSW + Scenarist) |
|
|
501
|
+
| **Debugging** | 🎯 Pinpoint Playwright integration issues | 🔍 Find framework integration issues |
|
|
502
|
+
| **Coverage** | Edge cases + error handling | Happy paths + real scenarios |
|
|
503
|
+
| **Dependencies** | Minimal (Playwright, MSW) | Many (Next.js, MSW client, Scenarist) |
|
|
504
|
+
| **What it proves** | Helper works with Playwright API | Helper works with real frameworks |
|
|
505
|
+
|
|
506
|
+
**Takeaway**: Package tests prove Playwright integration. Integration tests prove framework integration.
|
|
507
|
+
|
|
508
|
+
**Run Integration Tests**:
|
|
509
|
+
```bash
|
|
510
|
+
# From repository root
|
|
511
|
+
pnpm --filter=@scenarist/nextjs-pages-router-example test:e2e
|
|
512
|
+
```
|
|
513
|
+
|
|
514
|
+
### TDD Compliance
|
|
515
|
+
|
|
516
|
+
**Critical Question**: "If these aren't unit tests, why were they written AFTER the E2E tests?"
|
|
517
|
+
|
|
518
|
+
**Answer**: This follows strict TDD with **deliberate refactoring**:
|
|
519
|
+
|
|
520
|
+
**Phase 1a (RED)**: E2E test written first
|
|
521
|
+
- ❌ Test fails: "switchScenario is not a function"
|
|
522
|
+
- **This is the failing test that drove development**
|
|
523
|
+
|
|
524
|
+
**Phase 1b (GREEN)**: Minimum implementation
|
|
525
|
+
- ✅ Helper implementation created
|
|
526
|
+
- ✅ E2E test passes
|
|
527
|
+
- **Working code, ready to commit**
|
|
528
|
+
|
|
529
|
+
**Phase 1c (REFACTOR)**: Edge case coverage added
|
|
530
|
+
- 🔧 17 behavior tests added (error handling, edge cases, defaults)
|
|
531
|
+
- ✅ All tests green, 100% coverage achieved
|
|
532
|
+
- **Refactoring step per RED-GREEN-REFACTOR cycle**
|
|
533
|
+
|
|
534
|
+
**Key Insight**: Package tests are NOT "test-first" - they're REFACTORING tests added after green to ensure edge case coverage. The E2E test was the failing test that drove implementation.
|
|
535
|
+
|
|
536
|
+
This is textbook TDD: **RED** (E2E fails) → **GREEN** (implementation) → **REFACTOR** (add package tests for completeness).
|
|
537
|
+
|
|
538
|
+
### How This Aligns With Testing Guidelines
|
|
539
|
+
|
|
540
|
+
Our testing guidelines (from `docs/testing-guidelines.md`) require:
|
|
541
|
+
|
|
542
|
+
| Guideline | How Package Tests Comply |
|
|
543
|
+
|-----------|--------------------------|
|
|
544
|
+
| **"Test through public API exclusively"** | ✅ Tests call `switchScenario()` only - internals invisible |
|
|
545
|
+
| **"No 1:1 mapping between test/implementation files"** | ✅ Single test file, single public function, multiple behaviors |
|
|
546
|
+
| **"Tests must document expected business behaviour"** | ✅ Each test describes observable behavior (error, headers, defaults) |
|
|
547
|
+
| **"Behavior-driven - treat as black box"** | ✅ Tests verify inputs → outputs, implementation is opaque |
|
|
548
|
+
|
|
549
|
+
**Key Distinction**:
|
|
550
|
+
- ❌ **Unit testing** = Testing internal functions, mocking own code, coupling to implementation
|
|
551
|
+
- ✅ **Behavior testing** = Testing public API, mocking external dependencies, verifying outcomes
|
|
552
|
+
|
|
553
|
+
We mock Playwright's `Page` (external dependency we don't own), not our own code.
|
|
554
|
+
|
|
555
|
+
## Development
|
|
556
|
+
|
|
557
|
+
```bash
|
|
558
|
+
# Build the package
|
|
559
|
+
pnpm build
|
|
560
|
+
|
|
561
|
+
# Type check
|
|
562
|
+
pnpm typecheck
|
|
563
|
+
|
|
564
|
+
# Lint
|
|
565
|
+
pnpm lint
|
|
566
|
+
|
|
567
|
+
# Clean build artifacts
|
|
568
|
+
pnpm clean
|
|
569
|
+
```
|
|
570
|
+
|
|
571
|
+
## Why This Package Exists
|
|
572
|
+
|
|
573
|
+
Before this helper, switching scenarios in Playwright tests required significant boilerplate:
|
|
574
|
+
|
|
575
|
+
1. Generate unique test ID
|
|
576
|
+
2. Construct scenario endpoint URL
|
|
577
|
+
3. Send POST request with test ID header
|
|
578
|
+
4. Verify response status
|
|
579
|
+
5. Set test ID header for all subsequent requests
|
|
580
|
+
|
|
581
|
+
This 9-line pattern was repeated in every test, making tests verbose and error-prone. The `switchScenario` helper encapsulates this pattern into a single function call, reducing code by 77% while improving readability and maintainability.
|
|
582
|
+
|
|
583
|
+
## Documentation
|
|
584
|
+
|
|
585
|
+
📖 **[Full Documentation](https://scenarist.io)** - Complete guides, API reference, and examples.
|
|
586
|
+
|
|
587
|
+
## Contributing
|
|
588
|
+
|
|
589
|
+
See [CONTRIBUTING.md](../../CONTRIBUTING.md) for development setup and guidelines.
|
|
590
|
+
|
|
591
|
+
## License
|
|
592
|
+
|
|
593
|
+
MIT
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Playwright fixtures for Scenarist
|
|
3
|
+
*
|
|
4
|
+
* **Recommended API**: Use `withScenarios()` for type-safe scenario IDs with autocomplete.
|
|
5
|
+
*
|
|
6
|
+
* Provides custom fixtures for scenario management with guaranteed unique test IDs
|
|
7
|
+
* to prevent state collisions during parallel test execution.
|
|
8
|
+
*
|
|
9
|
+
* ## Basic Usage
|
|
10
|
+
*
|
|
11
|
+
* Configure once in playwright.config.ts:
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```typescript
|
|
15
|
+
* import { defineConfig } from '@playwright/test';
|
|
16
|
+
* import type { ScenaristOptions } from '@scenarist/playwright-helpers';
|
|
17
|
+
*
|
|
18
|
+
* export default defineConfig<ScenaristOptions>({
|
|
19
|
+
* use: {
|
|
20
|
+
* baseURL: 'http://localhost:3000',
|
|
21
|
+
* scenaristEndpoint: '/api/__scenario__',
|
|
22
|
+
* },
|
|
23
|
+
* });
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* Define scenarios and create typed test object:
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```typescript
|
|
30
|
+
* // tests/fixtures.ts
|
|
31
|
+
* import { withScenarios, expect } from '@scenarist/playwright-helpers';
|
|
32
|
+
* import { type ScenaristScenarios } from '@scenarist/core';
|
|
33
|
+
*
|
|
34
|
+
* const scenarios = {
|
|
35
|
+
* cartWithState: { id: 'cartWithState', name: 'Cart with State', ... },
|
|
36
|
+
* premiumUser: { id: 'premiumUser', name: 'Premium User', ... },
|
|
37
|
+
* } as const satisfies ScenaristScenarios;
|
|
38
|
+
*
|
|
39
|
+
* export const test = withScenarios(scenarios);
|
|
40
|
+
* export { expect };
|
|
41
|
+
* ```
|
|
42
|
+
*
|
|
43
|
+
* Then use in tests with type-safe scenario IDs:
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ```typescript
|
|
47
|
+
* import { test, expect } from './fixtures';
|
|
48
|
+
*
|
|
49
|
+
* test('my test', async ({ page, switchScenario }) => {
|
|
50
|
+
* await switchScenario(page, 'cartWithState'); // ✅ Autocomplete works!
|
|
51
|
+
* await switchScenario(page, 'invalid'); // ❌ TypeScript error
|
|
52
|
+
* });
|
|
53
|
+
* ```
|
|
54
|
+
*
|
|
55
|
+
* ## Composing with Existing Fixtures
|
|
56
|
+
*
|
|
57
|
+
* If your team already has custom fixtures, extend the test object:
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```typescript
|
|
61
|
+
* // tests/fixtures.ts
|
|
62
|
+
* import { withScenarios, expect } from '@scenarist/playwright-helpers';
|
|
63
|
+
* import { scenarios } from '../lib/scenarios';
|
|
64
|
+
*
|
|
65
|
+
* type MyFixtures = {
|
|
66
|
+
* myCustomFixture: string;
|
|
67
|
+
* };
|
|
68
|
+
*
|
|
69
|
+
* export const test = withScenarios(scenarios).extend<MyFixtures>({
|
|
70
|
+
* myCustomFixture: async ({}, use) => {
|
|
71
|
+
* await use('my custom value');
|
|
72
|
+
* },
|
|
73
|
+
* });
|
|
74
|
+
*
|
|
75
|
+
* export { expect };
|
|
76
|
+
* ```
|
|
77
|
+
*
|
|
78
|
+
* ## Advanced: Per-Test Overrides
|
|
79
|
+
*
|
|
80
|
+
* Override configuration for specific tests:
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* ```typescript
|
|
84
|
+
* test('staging test', async ({ page, switchScenario }) => {
|
|
85
|
+
* await switchScenario(page, 'cartWithState', {
|
|
86
|
+
* baseURL: 'https://staging.example.com',
|
|
87
|
+
* endpoint: '/api/custom-endpoint',
|
|
88
|
+
* });
|
|
89
|
+
* });
|
|
90
|
+
* ```
|
|
91
|
+
*
|
|
92
|
+
* For complete documentation, see the README at:
|
|
93
|
+
* https://github.com/citypaul/scenarist/tree/main/packages/playwright-helpers
|
|
94
|
+
*/
|
|
95
|
+
import { type Page } from '@playwright/test';
|
|
96
|
+
import { type SwitchScenarioOptions } from './switch-scenario.js';
|
|
97
|
+
import type { ScenaristScenarios, ScenarioIds } from '@scenarist/core';
|
|
98
|
+
/**
|
|
99
|
+
* Configuration options for Scenarist.
|
|
100
|
+
*
|
|
101
|
+
* Set these in your playwright.config.ts `use` object.
|
|
102
|
+
*/
|
|
103
|
+
export type ScenaristOptions = {
|
|
104
|
+
/**
|
|
105
|
+
* The endpoint where Scenarist listens for scenario switching requests.
|
|
106
|
+
*
|
|
107
|
+
* @default '/api/__scenario__'
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* ```typescript
|
|
111
|
+
* export default defineConfig({
|
|
112
|
+
* use: {
|
|
113
|
+
* scenaristEndpoint: '/api/__scenario__',
|
|
114
|
+
* },
|
|
115
|
+
* });
|
|
116
|
+
* ```
|
|
117
|
+
*/
|
|
118
|
+
scenaristEndpoint: string;
|
|
119
|
+
};
|
|
120
|
+
/**
|
|
121
|
+
* Fixtures provided by Scenarist for Playwright tests.
|
|
122
|
+
*
|
|
123
|
+
* Generic type parameter S allows constraining scenario IDs for type safety.
|
|
124
|
+
*/
|
|
125
|
+
export type ScenaristFixtures<S extends string = string> = {
|
|
126
|
+
/**
|
|
127
|
+
* Guaranteed unique test ID for this test.
|
|
128
|
+
* Uses crypto.randomUUID() to ensure no collisions even with parallel execution.
|
|
129
|
+
*
|
|
130
|
+
* @remarks
|
|
131
|
+
* You typically don't need to use this directly - the `switchScenario` fixture
|
|
132
|
+
* automatically injects it for you.
|
|
133
|
+
*/
|
|
134
|
+
scenaristTestId: string;
|
|
135
|
+
/**
|
|
136
|
+
* Switch to a scenario using this test's unique test ID.
|
|
137
|
+
*
|
|
138
|
+
* Reads `baseURL` (standard Playwright) and `scenaristEndpoint` from config.
|
|
139
|
+
* Can be overridden per-test if needed.
|
|
140
|
+
*
|
|
141
|
+
* @param page - Playwright Page object
|
|
142
|
+
* @param scenarioId - The scenario ID to switch to (constrained to S if createTest<S> was used)
|
|
143
|
+
* @param options - Optional overrides for endpoint and baseURL
|
|
144
|
+
* @returns The test ID used for this scenario (for explicit page.request calls)
|
|
145
|
+
*
|
|
146
|
+
* @example Basic usage (reads from config)
|
|
147
|
+
* ```typescript
|
|
148
|
+
* test('my test', async ({ page, switchScenario }) => {
|
|
149
|
+
* const testId = await switchScenario(page, 'myScenario');
|
|
150
|
+
* // Use testId for explicit API requests if needed
|
|
151
|
+
* });
|
|
152
|
+
* ```
|
|
153
|
+
*
|
|
154
|
+
* @example Override for specific test
|
|
155
|
+
* ```typescript
|
|
156
|
+
* test('staging test', async ({ page, switchScenario }) => {
|
|
157
|
+
* const testId = await switchScenario(page, 'myScenario', {
|
|
158
|
+
* baseURL: 'https://staging.example.com'
|
|
159
|
+
* });
|
|
160
|
+
* });
|
|
161
|
+
* ```
|
|
162
|
+
*/
|
|
163
|
+
switchScenario: (page: Page, scenarioId: S, options?: Partial<Pick<SwitchScenarioOptions, 'endpoint' | 'baseURL'>>) => Promise<string>;
|
|
164
|
+
};
|
|
165
|
+
/**
|
|
166
|
+
* Create a type-safe Playwright test object with Scenarist fixtures.
|
|
167
|
+
*
|
|
168
|
+
* Accepts a scenarios object and automatically infers scenario IDs for type safety.
|
|
169
|
+
* This is the ONLY way to create test objects with Scenarist - ensures consistency.
|
|
170
|
+
*
|
|
171
|
+
* @template T - Scenarios object type
|
|
172
|
+
*
|
|
173
|
+
* @example
|
|
174
|
+
* ```typescript
|
|
175
|
+
* // tests/fixtures.ts
|
|
176
|
+
* import { withScenarios, expect } from '@scenarist/playwright-helpers';
|
|
177
|
+
* import { type ScenaristScenarios } from '@scenarist/core';
|
|
178
|
+
*
|
|
179
|
+
* const scenarios = {
|
|
180
|
+
* cartWithState: { id: 'cartWithState', ... },
|
|
181
|
+
* premiumUser: { id: 'premiumUser', ... },
|
|
182
|
+
* } as const satisfies ScenaristScenarios;
|
|
183
|
+
*
|
|
184
|
+
* export const test = withScenarios(scenarios);
|
|
185
|
+
* export { expect };
|
|
186
|
+
*
|
|
187
|
+
* // tests/my-test.spec.ts
|
|
188
|
+
* import { test, expect } from './fixtures';
|
|
189
|
+
*
|
|
190
|
+
* test('my test', async ({ page, switchScenario }) => {
|
|
191
|
+
* await switchScenario(page, 'cartWithState'); // ✅ Autocomplete works!
|
|
192
|
+
* await switchScenario(page, 'invalid'); // ❌ TypeScript error
|
|
193
|
+
* });
|
|
194
|
+
* ```
|
|
195
|
+
*/
|
|
196
|
+
export declare function withScenarios<T extends ScenaristScenarios>(scenarios: T): import("@playwright/test").TestType<import("@playwright/test").PlaywrightTestArgs & import("@playwright/test").PlaywrightTestOptions & ScenaristOptions & ScenaristFixtures<ScenarioIds<T>>, import("@playwright/test").PlaywrightWorkerArgs & import("@playwright/test").PlaywrightWorkerOptions>;
|
|
197
|
+
export declare const expect: import("@playwright/test").Expect<{}>;
|
|
198
|
+
//# sourceMappingURL=fixtures.d.ts.map
|
|
@@ -0,0 +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"}
|
package/dist/fixtures.js
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Playwright fixtures for Scenarist
|
|
3
|
+
*
|
|
4
|
+
* **Recommended API**: Use `withScenarios()` for type-safe scenario IDs with autocomplete.
|
|
5
|
+
*
|
|
6
|
+
* Provides custom fixtures for scenario management with guaranteed unique test IDs
|
|
7
|
+
* to prevent state collisions during parallel test execution.
|
|
8
|
+
*
|
|
9
|
+
* ## Basic Usage
|
|
10
|
+
*
|
|
11
|
+
* Configure once in playwright.config.ts:
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```typescript
|
|
15
|
+
* import { defineConfig } from '@playwright/test';
|
|
16
|
+
* import type { ScenaristOptions } from '@scenarist/playwright-helpers';
|
|
17
|
+
*
|
|
18
|
+
* export default defineConfig<ScenaristOptions>({
|
|
19
|
+
* use: {
|
|
20
|
+
* baseURL: 'http://localhost:3000',
|
|
21
|
+
* scenaristEndpoint: '/api/__scenario__',
|
|
22
|
+
* },
|
|
23
|
+
* });
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* Define scenarios and create typed test object:
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```typescript
|
|
30
|
+
* // tests/fixtures.ts
|
|
31
|
+
* import { withScenarios, expect } from '@scenarist/playwright-helpers';
|
|
32
|
+
* import { type ScenaristScenarios } from '@scenarist/core';
|
|
33
|
+
*
|
|
34
|
+
* const scenarios = {
|
|
35
|
+
* cartWithState: { id: 'cartWithState', name: 'Cart with State', ... },
|
|
36
|
+
* premiumUser: { id: 'premiumUser', name: 'Premium User', ... },
|
|
37
|
+
* } as const satisfies ScenaristScenarios;
|
|
38
|
+
*
|
|
39
|
+
* export const test = withScenarios(scenarios);
|
|
40
|
+
* export { expect };
|
|
41
|
+
* ```
|
|
42
|
+
*
|
|
43
|
+
* Then use in tests with type-safe scenario IDs:
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ```typescript
|
|
47
|
+
* import { test, expect } from './fixtures';
|
|
48
|
+
*
|
|
49
|
+
* test('my test', async ({ page, switchScenario }) => {
|
|
50
|
+
* await switchScenario(page, 'cartWithState'); // ✅ Autocomplete works!
|
|
51
|
+
* await switchScenario(page, 'invalid'); // ❌ TypeScript error
|
|
52
|
+
* });
|
|
53
|
+
* ```
|
|
54
|
+
*
|
|
55
|
+
* ## Composing with Existing Fixtures
|
|
56
|
+
*
|
|
57
|
+
* If your team already has custom fixtures, extend the test object:
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```typescript
|
|
61
|
+
* // tests/fixtures.ts
|
|
62
|
+
* import { withScenarios, expect } from '@scenarist/playwright-helpers';
|
|
63
|
+
* import { scenarios } from '../lib/scenarios';
|
|
64
|
+
*
|
|
65
|
+
* type MyFixtures = {
|
|
66
|
+
* myCustomFixture: string;
|
|
67
|
+
* };
|
|
68
|
+
*
|
|
69
|
+
* export const test = withScenarios(scenarios).extend<MyFixtures>({
|
|
70
|
+
* myCustomFixture: async ({}, use) => {
|
|
71
|
+
* await use('my custom value');
|
|
72
|
+
* },
|
|
73
|
+
* });
|
|
74
|
+
*
|
|
75
|
+
* export { expect };
|
|
76
|
+
* ```
|
|
77
|
+
*
|
|
78
|
+
* ## Advanced: Per-Test Overrides
|
|
79
|
+
*
|
|
80
|
+
* Override configuration for specific tests:
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* ```typescript
|
|
84
|
+
* test('staging test', async ({ page, switchScenario }) => {
|
|
85
|
+
* await switchScenario(page, 'cartWithState', {
|
|
86
|
+
* baseURL: 'https://staging.example.com',
|
|
87
|
+
* endpoint: '/api/custom-endpoint',
|
|
88
|
+
* });
|
|
89
|
+
* });
|
|
90
|
+
* ```
|
|
91
|
+
*
|
|
92
|
+
* For complete documentation, see the README at:
|
|
93
|
+
* https://github.com/citypaul/scenarist/tree/main/packages/playwright-helpers
|
|
94
|
+
*/
|
|
95
|
+
import { test as base, expect as baseExpect } from '@playwright/test';
|
|
96
|
+
import { switchScenario as baseSwitchScenario } from './switch-scenario.js';
|
|
97
|
+
/**
|
|
98
|
+
* Create a type-safe Playwright test object with Scenarist fixtures.
|
|
99
|
+
*
|
|
100
|
+
* Accepts a scenarios object and automatically infers scenario IDs for type safety.
|
|
101
|
+
* This is the ONLY way to create test objects with Scenarist - ensures consistency.
|
|
102
|
+
*
|
|
103
|
+
* @template T - Scenarios object type
|
|
104
|
+
*
|
|
105
|
+
* @example
|
|
106
|
+
* ```typescript
|
|
107
|
+
* // tests/fixtures.ts
|
|
108
|
+
* import { withScenarios, expect } from '@scenarist/playwright-helpers';
|
|
109
|
+
* import { type ScenaristScenarios } from '@scenarist/core';
|
|
110
|
+
*
|
|
111
|
+
* const scenarios = {
|
|
112
|
+
* cartWithState: { id: 'cartWithState', ... },
|
|
113
|
+
* premiumUser: { id: 'premiumUser', ... },
|
|
114
|
+
* } as const satisfies ScenaristScenarios;
|
|
115
|
+
*
|
|
116
|
+
* export const test = withScenarios(scenarios);
|
|
117
|
+
* export { expect };
|
|
118
|
+
*
|
|
119
|
+
* // tests/my-test.spec.ts
|
|
120
|
+
* import { test, expect } from './fixtures';
|
|
121
|
+
*
|
|
122
|
+
* test('my test', async ({ page, switchScenario }) => {
|
|
123
|
+
* await switchScenario(page, 'cartWithState'); // ✅ Autocomplete works!
|
|
124
|
+
* await switchScenario(page, 'invalid'); // ❌ TypeScript error
|
|
125
|
+
* });
|
|
126
|
+
* ```
|
|
127
|
+
*/
|
|
128
|
+
export function withScenarios(scenarios) {
|
|
129
|
+
// Parameter required for TypeScript type inference (extracting ScenarioId type)
|
|
130
|
+
// but not used at runtime. Void statement satisfies noUnusedParameters.
|
|
131
|
+
void scenarios;
|
|
132
|
+
return base.extend({
|
|
133
|
+
// Configuration option with default value
|
|
134
|
+
scenaristEndpoint: ['/api/__scenario__', { option: true }],
|
|
135
|
+
// Generate a guaranteed unique test ID for each test
|
|
136
|
+
scenaristTestId: async ({}, use, testInfo) => {
|
|
137
|
+
// Use test info + UUID for guaranteed uniqueness
|
|
138
|
+
const uniqueId = `${testInfo.testId}-${crypto.randomUUID()}`;
|
|
139
|
+
await use(uniqueId);
|
|
140
|
+
},
|
|
141
|
+
// Provide a switchScenario helper that reads config and auto-injects test ID
|
|
142
|
+
switchScenario: async ({ scenaristTestId, scenaristEndpoint, baseURL }, use) => {
|
|
143
|
+
const switchFn = async (page, scenarioId, options) => {
|
|
144
|
+
// Read from config, allow per-test override, fallback to defaults
|
|
145
|
+
const finalEndpoint = options?.endpoint ?? scenaristEndpoint;
|
|
146
|
+
const finalBaseURL = options?.baseURL ?? baseURL ?? 'http://localhost:3000';
|
|
147
|
+
// Call the base switchScenario with all config and return test ID
|
|
148
|
+
return await baseSwitchScenario(page, scenarioId, {
|
|
149
|
+
endpoint: finalEndpoint,
|
|
150
|
+
baseURL: finalBaseURL,
|
|
151
|
+
testId: scenaristTestId,
|
|
152
|
+
});
|
|
153
|
+
};
|
|
154
|
+
await use(switchFn);
|
|
155
|
+
},
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
export const expect = baseExpect;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +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';
|
|
4
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +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"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { Page } from '@playwright/test';
|
|
2
|
+
/**
|
|
3
|
+
* Options for switchScenario helper
|
|
4
|
+
*/
|
|
5
|
+
export type SwitchScenarioOptions = {
|
|
6
|
+
/**
|
|
7
|
+
* Base URL of the application
|
|
8
|
+
* @example 'http://localhost:3000'
|
|
9
|
+
*/
|
|
10
|
+
readonly baseURL: string;
|
|
11
|
+
/**
|
|
12
|
+
* Scenario endpoint path
|
|
13
|
+
* @default '/__scenario__'
|
|
14
|
+
*/
|
|
15
|
+
readonly endpoint?: string;
|
|
16
|
+
/**
|
|
17
|
+
* Optional test ID to use instead of auto-generating one.
|
|
18
|
+
* When using the fixture-based API, this is automatically provided.
|
|
19
|
+
* @internal
|
|
20
|
+
*/
|
|
21
|
+
readonly testId?: string;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Switch to a different scenario in Playwright tests.
|
|
25
|
+
*
|
|
26
|
+
* This helper simplifies scenario switching by:
|
|
27
|
+
* - Automatically generating a unique test ID
|
|
28
|
+
* - Calling the scenario endpoint
|
|
29
|
+
* - Setting test ID headers for subsequent requests
|
|
30
|
+
*
|
|
31
|
+
* @param page - Playwright Page object
|
|
32
|
+
* @param scenarioId - Scenario ID to switch to
|
|
33
|
+
* @param options - Configuration options
|
|
34
|
+
* @returns Promise that resolves with the test ID used for this scenario
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```typescript
|
|
38
|
+
* import { switchScenario } from '@scenarist/playwright-helpers';
|
|
39
|
+
*
|
|
40
|
+
* test('premium user flow', async ({ page }) => {
|
|
41
|
+
* const testId = await switchScenario(page, 'premiumUser', {
|
|
42
|
+
* baseURL: 'http://localhost:3000',
|
|
43
|
+
* });
|
|
44
|
+
*
|
|
45
|
+
* // Use testId for explicit API requests
|
|
46
|
+
* await page.request.post('/api/action', {
|
|
47
|
+
* headers: { 'x-scenarist-test-id': testId },
|
|
48
|
+
* });
|
|
49
|
+
*
|
|
50
|
+
* await page.goto('/');
|
|
51
|
+
* // Test with premium user scenario active
|
|
52
|
+
* });
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
export declare const switchScenario: (page: Page, scenarioId: string, options: SwitchScenarioOptions) => Promise<string>;
|
|
56
|
+
//# sourceMappingURL=switch-scenario.d.ts.map
|
|
@@ -0,0 +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"}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { SCENARIST_TEST_ID_HEADER } from '@scenarist/core';
|
|
2
|
+
/**
|
|
3
|
+
* Establish route interception and header injection for test ID propagation.
|
|
4
|
+
*
|
|
5
|
+
* CRITICAL: Must be called BEFORE navigation to prevent race conditions.
|
|
6
|
+
* Client Components may fire API calls immediately on mount, and if route
|
|
7
|
+
* interception isn't established first, those requests bypass MSW.
|
|
8
|
+
*
|
|
9
|
+
* @param page - Playwright Page object
|
|
10
|
+
* @param testId - Test ID to inject into all requests
|
|
11
|
+
*/
|
|
12
|
+
const establishTestIdInterception = async (page, testId) => {
|
|
13
|
+
// Clear any existing handlers to prevent accumulation
|
|
14
|
+
await page.unroute('**/*');
|
|
15
|
+
// Intercept all routes to inject test ID header
|
|
16
|
+
await page.route('**/*', async (route) => {
|
|
17
|
+
const headers = route.request().headers();
|
|
18
|
+
headers[SCENARIST_TEST_ID_HEADER] = testId;
|
|
19
|
+
await route.continue({ headers });
|
|
20
|
+
});
|
|
21
|
+
// Set test ID header for navigation requests (belt and suspenders)
|
|
22
|
+
await page.setExtraHTTPHeaders({ [SCENARIST_TEST_ID_HEADER]: testId });
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Switch to a different scenario in Playwright tests.
|
|
26
|
+
*
|
|
27
|
+
* This helper simplifies scenario switching by:
|
|
28
|
+
* - Automatically generating a unique test ID
|
|
29
|
+
* - Calling the scenario endpoint
|
|
30
|
+
* - Setting test ID headers for subsequent requests
|
|
31
|
+
*
|
|
32
|
+
* @param page - Playwright Page object
|
|
33
|
+
* @param scenarioId - Scenario ID to switch to
|
|
34
|
+
* @param options - Configuration options
|
|
35
|
+
* @returns Promise that resolves with the test ID used for this scenario
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```typescript
|
|
39
|
+
* import { switchScenario } from '@scenarist/playwright-helpers';
|
|
40
|
+
*
|
|
41
|
+
* test('premium user flow', async ({ page }) => {
|
|
42
|
+
* const testId = await switchScenario(page, 'premiumUser', {
|
|
43
|
+
* baseURL: 'http://localhost:3000',
|
|
44
|
+
* });
|
|
45
|
+
*
|
|
46
|
+
* // Use testId for explicit API requests
|
|
47
|
+
* await page.request.post('/api/action', {
|
|
48
|
+
* headers: { 'x-scenarist-test-id': testId },
|
|
49
|
+
* });
|
|
50
|
+
*
|
|
51
|
+
* await page.goto('/');
|
|
52
|
+
* // Test with premium user scenario active
|
|
53
|
+
* });
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
export const switchScenario = async (page, scenarioId, options) => {
|
|
57
|
+
const { baseURL, endpoint = '/__scenario__', testId: providedTestId, } = options;
|
|
58
|
+
// Use provided test ID (from fixture) or generate unique one
|
|
59
|
+
// When using fixtures, test ID is guaranteed unique by Playwright's test context
|
|
60
|
+
// Date.now() can collide when tests run in parallel within the same millisecond
|
|
61
|
+
const testId = providedTestId ?? `test-${scenarioId}-${crypto.randomUUID()}`;
|
|
62
|
+
// Establish test ID interception BEFORE scenario switch to prevent race conditions
|
|
63
|
+
// Client Components may fire API calls immediately on mount/navigation
|
|
64
|
+
await establishTestIdInterception(page, testId);
|
|
65
|
+
// Call scenario endpoint
|
|
66
|
+
const url = `${baseURL}${endpoint}`;
|
|
67
|
+
const response = await page.request.post(url, {
|
|
68
|
+
headers: { [SCENARIST_TEST_ID_HEADER]: testId },
|
|
69
|
+
data: {
|
|
70
|
+
scenario: scenarioId,
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
// Verify scenario switch succeeded
|
|
74
|
+
if (response.status() !== 200) {
|
|
75
|
+
const body = await response.text();
|
|
76
|
+
throw new Error(`Failed to switch scenario: ${response.status()} ${response.statusText()}\n${body}`);
|
|
77
|
+
}
|
|
78
|
+
// Return test ID for explicit use in page.request calls
|
|
79
|
+
return testId;
|
|
80
|
+
};
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Type definitions for Scenarist Playwright helpers
|
|
3
|
+
*
|
|
4
|
+
* This file will contain type definitions for the helpers package.
|
|
5
|
+
* Currently empty - to be implemented in Phase 1.
|
|
6
|
+
*/
|
|
7
|
+
export type ScenaristFixtures = Record<string, never>;
|
|
8
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,MAAM,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC"}
|
package/dist/types.js
ADDED
package/dist/utils.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Utility functions for Scenarist Playwright helpers
|
|
3
|
+
*
|
|
4
|
+
* This file will contain utility functions for test ID generation and scenario switching.
|
|
5
|
+
* Currently empty - to be implemented in Phase 1.
|
|
6
|
+
*/
|
|
7
|
+
export declare const placeholder = true;
|
|
8
|
+
//# sourceMappingURL=utils.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,eAAO,MAAM,WAAW,OAAO,CAAC"}
|
package/dist/utils.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Utility functions for Scenarist Playwright helpers
|
|
3
|
+
*
|
|
4
|
+
* This file will contain utility functions for test ID generation and scenario switching.
|
|
5
|
+
* Currently empty - to be implemented in Phase 1.
|
|
6
|
+
*/
|
|
7
|
+
// Placeholder - to be implemented
|
|
8
|
+
export const placeholder = true;
|
package/package.json
CHANGED
|
@@ -1,10 +1,65 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@scenarist/playwright-helpers",
|
|
3
|
-
"version": "0.0
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Playwright test helpers for Scenarist scenario management",
|
|
5
|
+
"author": "Paul Hammond (citypaul) <paul@packsoftware.co.uk>",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"homepage": "https://github.com/citypaul/scenarist#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "https://github.com/citypaul/scenarist.git",
|
|
11
|
+
"directory": "packages/playwright-helpers"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/citypaul/scenarist/issues"
|
|
15
|
+
},
|
|
5
16
|
"keywords": [
|
|
6
|
-
"
|
|
7
|
-
"
|
|
8
|
-
"
|
|
9
|
-
|
|
10
|
-
|
|
17
|
+
"playwright",
|
|
18
|
+
"testing",
|
|
19
|
+
"test-helpers",
|
|
20
|
+
"scenario-testing",
|
|
21
|
+
"msw",
|
|
22
|
+
"mock-service-worker",
|
|
23
|
+
"e2e-testing",
|
|
24
|
+
"integration-testing",
|
|
25
|
+
"typescript"
|
|
26
|
+
],
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=18.0.0"
|
|
29
|
+
},
|
|
30
|
+
"type": "module",
|
|
31
|
+
"sideEffects": false,
|
|
32
|
+
"exports": {
|
|
33
|
+
".": {
|
|
34
|
+
"types": "./dist/index.d.ts",
|
|
35
|
+
"import": "./dist/index.js"
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
"files": [
|
|
39
|
+
"dist",
|
|
40
|
+
"README.md",
|
|
41
|
+
"LICENSE"
|
|
42
|
+
],
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"@playwright/test": "^1.48.2",
|
|
45
|
+
"@scenarist/core": "0.0.0"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@types/node": "^24.10.1",
|
|
49
|
+
"msw": "^2.12.1",
|
|
50
|
+
"typescript": "^5.9.3",
|
|
51
|
+
"@scenarist/eslint-config": "0.0.0",
|
|
52
|
+
"@scenarist/typescript-config": "0.0.0"
|
|
53
|
+
},
|
|
54
|
+
"publishConfig": {
|
|
55
|
+
"access": "public"
|
|
56
|
+
},
|
|
57
|
+
"scripts": {
|
|
58
|
+
"build": "tsc",
|
|
59
|
+
"clean": "rm -rf dist",
|
|
60
|
+
"test": "playwright test",
|
|
61
|
+
"test:watch": "playwright test --ui",
|
|
62
|
+
"typecheck": "tsc --noEmit",
|
|
63
|
+
"lint": "eslint ."
|
|
64
|
+
}
|
|
65
|
+
}
|