@scenarist/playwright-helpers 0.3.2 → 0.4.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/README.md CHANGED
@@ -312,6 +312,8 @@ test("my test", async ({ page, switchScenario, scenaristTestId }) => {
312
312
 
313
313
  - `switchScenario(page, scenarioId, options?)` - Switch to a scenario (auto-injects test ID)
314
314
  - `scenaristTestId` - Unique test ID for this test (usually don't need to access directly)
315
+ - `debugState(page)` - Get current test state from debug endpoint (useful for debugging)
316
+ - `waitForDebugState(page, condition, options?)` - Wait for state to meet a condition
315
317
 
316
318
  #### `expect`
317
319
 
@@ -337,6 +339,7 @@ export default defineConfig({
337
339
  **Available options:**
338
340
 
339
341
  - `scenaristEndpoint?: string` - The endpoint path or absolute URL for scenario switching (default: `'/api/__scenario__'`)
342
+ - `scenaristStateEndpoint?: string` - The endpoint path for debug state inspection (default: `'/__scenarist__/state'`)
340
343
 
341
344
  ### Cross-Origin API Servers
342
345
 
@@ -364,6 +367,112 @@ This is useful when:
364
367
  - You're testing against a staging/production API endpoint
365
368
  - Your test infrastructure uses a separate mock server
366
369
 
370
+ ### Debug State Fixtures
371
+
372
+ When testing multi-stage flows with state-aware mocking, you may need to inspect or wait for internal state changes. The `debugState` and `waitForDebugState` fixtures help debug test failures and verify state mutations.
373
+
374
+ #### `debugState` (Fixture)
375
+
376
+ Fetches the current test state from the debug endpoint. Useful for debugging and verifying `afterResponse.setState` worked correctly.
377
+
378
+ ```typescript
379
+ import { test, expect } from "./fixtures";
380
+
381
+ test("loan application flow", async ({ page, switchScenario, debugState }) => {
382
+ await switchScenario(page, "loanApplication");
383
+
384
+ // Before any actions - state should be empty
385
+ const initialState = await debugState(page);
386
+ expect(initialState).toEqual({});
387
+
388
+ // Navigate and submit application
389
+ await page.goto("/apply");
390
+ await page.getByRole("button", { name: "Submit" }).click();
391
+
392
+ // Verify state was set by afterResponse.setState
393
+ const state = await debugState(page);
394
+ expect(state.submitted).toBe(true);
395
+ expect(state.phase).toBe("review");
396
+ });
397
+ ```
398
+
399
+ **When to use `debugState`:**
400
+
401
+ - Debugging failing tests ("why is the response wrong?")
402
+ - Verifying `afterResponse.setState` worked correctly
403
+ - Understanding state progression through multi-step flows
404
+ - Testing conditional `afterResponse` behavior
405
+
406
+ #### `waitForDebugState` (Fixture)
407
+
408
+ Waits for the test state to meet a condition. Useful for async flows where state changes after a delay.
409
+
410
+ ```typescript
411
+ import { test, expect } from "./fixtures";
412
+
413
+ test("async approval flow", async ({
414
+ page,
415
+ switchScenario,
416
+ waitForDebugState,
417
+ }) => {
418
+ await switchScenario(page, "asyncApproval");
419
+ await page.goto("/dashboard");
420
+
421
+ // Trigger async approval process
422
+ await page.getByRole("button", { name: "Request Approval" }).click();
423
+
424
+ // Wait for state to indicate approval completed
425
+ const state = await waitForDebugState(
426
+ page,
427
+ (s) => s.approved === true,
428
+ { timeout: 10000 }, // Wait up to 10 seconds
429
+ );
430
+
431
+ expect(state.approved).toBe(true);
432
+ expect(state.approvedBy).toBeDefined();
433
+ });
434
+ ```
435
+
436
+ **Parameters:**
437
+
438
+ - `page: Page` - Playwright Page object
439
+ - `condition: (state: Record<string, unknown>) => boolean` - Function that returns true when state is ready
440
+ - `options?: { timeout?: number; interval?: number }` - Optional configuration
441
+ - `timeout` - Maximum time to wait in ms (default: 5000)
442
+ - `interval` - Polling interval in ms (default: 100)
443
+
444
+ **Throws:** Error if condition is not met within timeout.
445
+
446
+ #### Setting Up the Debug Endpoint
447
+
448
+ The debug fixtures require a debug state endpoint in your application. Create it alongside your scenario endpoint:
449
+
450
+ **Pages Router:**
451
+
452
+ ```typescript
453
+ // pages/api/__scenarist__/state.ts
454
+ import { scenarist } from "@/lib/scenarist";
455
+
456
+ export default scenarist?.createStateEndpoint();
457
+ ```
458
+
459
+ **App Router:**
460
+
461
+ ```typescript
462
+ // app/api/%5F%5Fscenarist%5F%5F/state/route.ts
463
+ import { scenarist } from "@/lib/scenarist";
464
+
465
+ const handler = scenarist?.createStateEndpoint();
466
+ export const GET = handler;
467
+ ```
468
+
469
+ **Express:**
470
+
471
+ ```typescript
472
+ // The state endpoint is automatically included in scenarist.middleware
473
+ // No additional setup needed!
474
+ ```
475
+
367
476
  #### `switchScenario` (Fixture)
368
477
 
369
478
  Switch to a scenario using the automatically generated test ID.
@@ -116,6 +116,36 @@ export type ScenaristOptions = {
116
116
  * ```
117
117
  */
118
118
  scenaristEndpoint: string;
119
+ /**
120
+ * The endpoint for retrieving test state (for debugging).
121
+ *
122
+ * @default '/__scenarist__/state'
123
+ *
124
+ * @example
125
+ * ```typescript
126
+ * export default defineConfig({
127
+ * use: {
128
+ * scenaristStateEndpoint: '/__scenarist__/state',
129
+ * },
130
+ * });
131
+ * ```
132
+ */
133
+ scenaristStateEndpoint: string;
134
+ };
135
+ /**
136
+ * Options for waitForDebugState fixture.
137
+ */
138
+ export type WaitForDebugStateOptions = {
139
+ /**
140
+ * Maximum time to wait in milliseconds.
141
+ * @default 5000
142
+ */
143
+ timeout?: number;
144
+ /**
145
+ * Polling interval in milliseconds.
146
+ * @default 100
147
+ */
148
+ interval?: number;
119
149
  };
120
150
  /**
121
151
  * Fixtures provided by Scenarist for Playwright tests.
@@ -161,6 +191,61 @@ export type ScenaristFixtures<S extends string = string> = {
161
191
  * ```
162
192
  */
163
193
  switchScenario: (page: Page, scenarioId: S, options?: Partial<Pick<SwitchScenarioOptions, "endpoint" | "baseURL">>) => Promise<string>;
194
+ /**
195
+ * Fetches current test state from the debug endpoint.
196
+ *
197
+ * Useful for debugging state flow in tests - inspect what state
198
+ * was set by afterResponse.setState.
199
+ *
200
+ * @param page - Playwright Page object (used for request context)
201
+ * @returns The current state object for this test ID
202
+ *
203
+ * @example
204
+ * ```typescript
205
+ * test('loan application flow', async ({ page, switchScenario, debugState }) => {
206
+ * await switchScenario(page, 'loanApplication');
207
+ * await page.goto('/apply');
208
+ * await page.fill('[name="amount"]', '10000');
209
+ * await page.click('button[type="submit"]');
210
+ *
211
+ * // Check what state was set after submission
212
+ * const state = await debugState(page);
213
+ * expect(state.phase).toBe('submitted');
214
+ * });
215
+ * ```
216
+ */
217
+ debugState: (page: Page) => Promise<Record<string, unknown>>;
218
+ /**
219
+ * Waits for test state to meet a condition.
220
+ *
221
+ * Useful for debugging async state transitions - wait for backend
222
+ * state to stabilize before asserting.
223
+ *
224
+ * @param page - Playwright Page object (used for request context)
225
+ * @param condition - Predicate function that returns true when condition is met
226
+ * @param options - Timeout and polling interval options
227
+ * @returns The state object that satisfied the condition
228
+ * @throws Error if timeout is reached before condition is met
229
+ *
230
+ * @example
231
+ * ```typescript
232
+ * test('async approval flow', async ({ page, switchScenario, waitForDebugState }) => {
233
+ * await switchScenario(page, 'approvalFlow');
234
+ * await page.goto('/dashboard');
235
+ * await page.click('#submit-for-approval');
236
+ *
237
+ * // Wait for state to indicate approval completed
238
+ * const state = await waitForDebugState(
239
+ * page,
240
+ * (s) => s.approved === true,
241
+ * { timeout: 10000 },
242
+ * );
243
+ *
244
+ * expect(state.approved).toBe(true);
245
+ * });
246
+ * ```
247
+ */
248
+ waitForDebugState: (page: Page, condition: (state: Record<string, unknown>) => boolean, options?: WaitForDebugStateOptions) => Promise<Record<string, unknown>>;
164
249
  };
165
250
  /**
166
251
  * 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,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;AAC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MAAM,wBAAwB,GAAG;IACrC;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,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;IAErB;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACH,UAAU,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA6BG;IACH,iBAAiB,EAAE,CACjB,IAAI,EAAE,IAAI,EACV,SAAS,EAAE,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,OAAO,EACtD,OAAO,CAAC,EAAE,wBAAwB,KAC/B,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CACvC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,aAAa,CAAC,CAAC,SAAS,kBAAkB,EAAE,SAAS,EAAE,CAAC,sSAuHvE;AAED,eAAO,MAAM,MAAM,uCAAa,CAAC"}
package/dist/fixtures.js CHANGED
@@ -130,8 +130,9 @@ export function withScenarios(scenarios) {
130
130
  // but not used at runtime. Void statement satisfies noUnusedParameters.
131
131
  void scenarios;
132
132
  return base.extend({
133
- // Configuration option with default value
133
+ // Configuration options with default values
134
134
  scenaristEndpoint: ["/api/__scenario__", { option: true }],
135
+ scenaristStateEndpoint: ["/__scenarist__/state", { option: true }],
135
136
  // Generate a guaranteed unique test ID for each test
136
137
  // eslint-disable-next-line no-empty-pattern -- Playwright requires object destructuring pattern
137
138
  scenaristTestId: async ({}, use, testInfo) => {
@@ -154,6 +155,53 @@ export function withScenarios(scenarios) {
154
155
  };
155
156
  await use(switchFn);
156
157
  },
158
+ // Debug state fixture - fetches current test state
159
+ debugState: async ({ scenaristTestId, scenaristStateEndpoint, baseURL }, use) => {
160
+ const debugFn = async (page) => {
161
+ const finalBaseURL = baseURL ?? "http://localhost:3000";
162
+ const url = `${finalBaseURL}${scenaristStateEndpoint}`;
163
+ const response = await page.request.get(url, {
164
+ headers: { "x-scenarist-test-id": scenaristTestId },
165
+ });
166
+ if (!response.ok()) {
167
+ throw new Error(`Failed to get debug state: ${response.status()}`);
168
+ }
169
+ const result = await response.json();
170
+ // Validate response structure at runtime before type narrowing
171
+ if (typeof result !== "object" ||
172
+ result === null ||
173
+ !("state" in result)) {
174
+ throw new Error("Invalid debug state response format");
175
+ }
176
+ // Runtime validation ensures 'state' property exists
177
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- runtime validated above
178
+ const typedResult = result;
179
+ if (typeof typedResult.state !== "object" ||
180
+ typedResult.state === null) {
181
+ return {};
182
+ }
183
+ // State is validated as object, return with proper type
184
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- runtime validated above
185
+ return typedResult.state;
186
+ };
187
+ await use(debugFn);
188
+ },
189
+ // Wait for debug state fixture - polls until condition is met
190
+ waitForDebugState: async ({ debugState }, use) => {
191
+ const waitFn = async (page, condition, options) => {
192
+ const { timeout = 5000, interval = 100 } = options ?? {};
193
+ const start = Date.now();
194
+ while (Date.now() - start < timeout) {
195
+ const state = await debugState(page);
196
+ if (condition(state)) {
197
+ return state;
198
+ }
199
+ await page.waitForTimeout(interval);
200
+ }
201
+ throw new Error(`Debug state condition not met within ${timeout}ms (timeout)`);
202
+ };
203
+ await use(waitFn);
204
+ },
157
205
  });
158
206
  }
159
207
  export const expect = baseExpect;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export { switchScenario, type SwitchScenarioOptions, } from "./switch-scenario.js";
2
- export { withScenarios, expect, type ScenaristOptions, type ScenaristFixtures, } from "./fixtures.js";
2
+ export { withScenarios, expect, type ScenaristOptions, type ScenaristFixtures, type WaitForDebugStateOptions, } from "./fixtures.js";
3
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,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"}
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,EACtB,KAAK,wBAAwB,GAC9B,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scenarist/playwright-helpers",
3
- "version": "0.3.2",
3
+ "version": "0.4.0",
4
4
  "description": "Playwright test helpers for Scenarist scenario management",
5
5
  "author": "Paul Hammond (citypaul) <paul@packsoftware.co.uk>",
6
6
  "license": "MIT",
@@ -43,7 +43,7 @@
43
43
  "LICENSE"
44
44
  ],
45
45
  "dependencies": {
46
- "@scenarist/core": "0.3.2"
46
+ "@scenarist/core": "0.4.0"
47
47
  },
48
48
  "peerDependencies": {
49
49
  "@playwright/test": "^1.0.0"