@scenarist/express-adapter 0.1.6 → 0.1.8
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 +220 -157
- package/dist/context/express-request-context.d.ts +2 -2
- package/dist/context/express-request-context.d.ts.map +1 -1
- package/dist/context/express-request-context.js +2 -2
- package/dist/index.d.ts +7 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -5
- package/dist/middleware/test-id-middleware.d.ts +3 -3
- package/dist/middleware/test-id-middleware.d.ts.map +1 -1
- package/dist/middleware/test-id-middleware.js +2 -2
- package/dist/setup/impl.d.ts +2 -2
- package/dist/setup/impl.d.ts.map +1 -1
- package/dist/setup/impl.js +17 -9
- package/dist/setup/production.d.ts +2 -2
- package/dist/setup/setup-scenarist.d.ts +2 -2
- package/dist/setup/setup-scenarist.js +2 -2
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -10,49 +10,59 @@ Express.js adapter for [Scenarist](https://scenarist.io) - manage MSW mock scena
|
|
|
10
10
|
**Scenarist** enables concurrent tests to run with different backend states by switching mock scenarios at runtime via test IDs. Your real application code executes while external API responses are controlled by scenarios. No application restarts needed, no complex per-test mocking, just simple scenario switching.
|
|
11
11
|
|
|
12
12
|
**Before Scenarist:**
|
|
13
|
+
|
|
13
14
|
```typescript
|
|
14
15
|
// Every test has fragile per-test mocking
|
|
15
16
|
beforeEach(() => {
|
|
16
|
-
server.use(
|
|
17
|
-
http.get('/api/user', () => HttpResponse.json({ role: 'admin' }))
|
|
18
|
-
);
|
|
17
|
+
server.use(http.get("/api/user", () => HttpResponse.json({ role: "admin" })));
|
|
19
18
|
});
|
|
20
19
|
// Repeat 100 times across test files, hope they don't conflict
|
|
21
20
|
```
|
|
22
21
|
|
|
23
22
|
**With Scenarist:**
|
|
23
|
+
|
|
24
24
|
```typescript
|
|
25
25
|
// Define scenario once
|
|
26
|
-
const adminScenario = {
|
|
26
|
+
const adminScenario = {
|
|
27
|
+
id: "admin",
|
|
28
|
+
mocks: [
|
|
29
|
+
/* complete backend state */
|
|
30
|
+
],
|
|
31
|
+
};
|
|
27
32
|
|
|
28
33
|
// Use in any test with one line
|
|
29
|
-
await setScenario(
|
|
34
|
+
await setScenario("test-1", "admin");
|
|
30
35
|
// Test runs with complete "admin" backend state, isolated from other tests
|
|
31
36
|
```
|
|
32
37
|
|
|
33
38
|
## Why Use Scenarist with Express?
|
|
34
39
|
|
|
35
40
|
**Runtime Scenario Switching**
|
|
41
|
+
|
|
36
42
|
- Change entire backend state with one API call
|
|
37
43
|
- No server restarts between tests
|
|
38
44
|
- Instant feedback during development
|
|
39
45
|
|
|
40
46
|
**True Parallel Testing**
|
|
47
|
+
|
|
41
48
|
- 100+ tests run concurrently with different scenarios
|
|
42
49
|
- Each test ID has isolated scenario state
|
|
43
50
|
- No conflicts, no serialization needed
|
|
44
51
|
|
|
45
52
|
**Automatic Test ID Propagation** (Express advantage)
|
|
53
|
+
|
|
46
54
|
- AsyncLocalStorage propagates test IDs automatically
|
|
47
55
|
- No manual header forwarding in route handlers
|
|
48
56
|
- MSW handlers receive test ID transparently
|
|
49
57
|
|
|
50
58
|
**Reusable Scenarios**
|
|
59
|
+
|
|
51
60
|
- Define scenarios once, use across all tests
|
|
52
61
|
- Version control your mock scenarios
|
|
53
62
|
- Share scenarios across teams
|
|
54
63
|
|
|
55
64
|
**Zero Boilerplate**
|
|
65
|
+
|
|
56
66
|
- One function call (`createScenarist()`) wires everything
|
|
57
67
|
- Middleware + endpoints + MSW automatically configured
|
|
58
68
|
- Just add `app.use(scenarist.middleware)` and you're done
|
|
@@ -83,6 +93,7 @@ yarn add -D @scenarist/express-adapter msw
|
|
|
83
93
|
**Note:** All Scenarist types (`ScenaristScenario`, `ScenaristMock`, etc.) are re-exported from `@scenarist/express-adapter` for convenience. You don't need to install `@scenarist/core` or `@scenarist/msw-adapter` separately - they're already included as dependencies.
|
|
84
94
|
|
|
85
95
|
**Peer Dependencies:**
|
|
96
|
+
|
|
86
97
|
- `express` ^4.18.0 || ^5.0.0
|
|
87
98
|
- `msw` ^2.0.0
|
|
88
99
|
|
|
@@ -90,13 +101,13 @@ yarn add -D @scenarist/express-adapter msw
|
|
|
90
101
|
|
|
91
102
|
**Full documentation at [scenarist.io](https://scenarist.io)**
|
|
92
103
|
|
|
93
|
-
| Topic
|
|
94
|
-
|
|
95
|
-
| **Why Scenarist?**
|
|
104
|
+
| Topic | Link |
|
|
105
|
+
| ----------------------------- | ---------------------------------------------------------------------------------------------------------- |
|
|
106
|
+
| **Why Scenarist?** | [scenarist.io/getting-started/why-scenarist](https://scenarist.io/getting-started/why-scenarist) |
|
|
96
107
|
| **Getting Started (Express)** | [scenarist.io/frameworks/express/getting-started](https://scenarist.io/frameworks/express/getting-started) |
|
|
97
|
-
| **Parallel Testing**
|
|
98
|
-
| **Testing Philosophy**
|
|
99
|
-
| **Architecture**
|
|
108
|
+
| **Parallel Testing** | [scenarist.io/testing/parallel-testing](https://scenarist.io/testing/parallel-testing) |
|
|
109
|
+
| **Testing Philosophy** | [scenarist.io/concepts/philosophy](https://scenarist.io/concepts/philosophy) |
|
|
110
|
+
| **Architecture** | [scenarist.io/concepts/architecture](https://scenarist.io/concepts/architecture) |
|
|
100
111
|
|
|
101
112
|
## Quick Start
|
|
102
113
|
|
|
@@ -104,22 +115,25 @@ yarn add -D @scenarist/express-adapter msw
|
|
|
104
115
|
|
|
105
116
|
```typescript
|
|
106
117
|
// test/scenarios.ts
|
|
107
|
-
import type {
|
|
118
|
+
import type {
|
|
119
|
+
ScenaristScenario,
|
|
120
|
+
ScenaristScenarios,
|
|
121
|
+
} from "@scenarist/express-adapter";
|
|
108
122
|
|
|
109
123
|
const defaultScenario: ScenaristScenario = {
|
|
110
|
-
id:
|
|
111
|
-
name:
|
|
112
|
-
description:
|
|
124
|
+
id: "default",
|
|
125
|
+
name: "Default Scenario",
|
|
126
|
+
description: "Baseline responses for all APIs",
|
|
113
127
|
mocks: [
|
|
114
128
|
{
|
|
115
|
-
method:
|
|
116
|
-
url:
|
|
129
|
+
method: "GET",
|
|
130
|
+
url: "https://api.example.com/user",
|
|
117
131
|
response: {
|
|
118
132
|
status: 200,
|
|
119
133
|
body: {
|
|
120
|
-
id:
|
|
121
|
-
name:
|
|
122
|
-
role:
|
|
134
|
+
id: "000",
|
|
135
|
+
name: "Default User",
|
|
136
|
+
role: "user",
|
|
123
137
|
},
|
|
124
138
|
},
|
|
125
139
|
},
|
|
@@ -127,19 +141,19 @@ const defaultScenario: ScenaristScenario = {
|
|
|
127
141
|
};
|
|
128
142
|
|
|
129
143
|
const adminUserScenario: ScenaristScenario = {
|
|
130
|
-
id:
|
|
131
|
-
name:
|
|
132
|
-
description:
|
|
144
|
+
id: "admin-user",
|
|
145
|
+
name: "Admin User",
|
|
146
|
+
description: "User with admin privileges",
|
|
133
147
|
mocks: [
|
|
134
148
|
{
|
|
135
|
-
method:
|
|
136
|
-
url:
|
|
149
|
+
method: "GET",
|
|
150
|
+
url: "https://api.example.com/user",
|
|
137
151
|
response: {
|
|
138
152
|
status: 200,
|
|
139
153
|
body: {
|
|
140
|
-
id:
|
|
141
|
-
name:
|
|
142
|
-
role:
|
|
154
|
+
id: "123",
|
|
155
|
+
name: "Admin User",
|
|
156
|
+
role: "admin",
|
|
143
157
|
},
|
|
144
158
|
},
|
|
145
159
|
},
|
|
@@ -157,12 +171,12 @@ export const scenarios = {
|
|
|
157
171
|
|
|
158
172
|
```typescript
|
|
159
173
|
// test/setup.ts
|
|
160
|
-
import { createScenarist } from
|
|
161
|
-
import { scenarios } from
|
|
174
|
+
import { createScenarist } from "@scenarist/express-adapter";
|
|
175
|
+
import { scenarios } from "./scenarios";
|
|
162
176
|
|
|
163
177
|
export const scenarist = createScenarist({
|
|
164
|
-
enabled: process.env.NODE_ENV ===
|
|
165
|
-
scenarios,
|
|
178
|
+
enabled: process.env.NODE_ENV === "test",
|
|
179
|
+
scenarios, // All scenarios registered upfront
|
|
166
180
|
strictMode: false,
|
|
167
181
|
});
|
|
168
182
|
```
|
|
@@ -171,20 +185,20 @@ export const scenarist = createScenarist({
|
|
|
171
185
|
|
|
172
186
|
```typescript
|
|
173
187
|
// src/app.ts
|
|
174
|
-
import express from
|
|
175
|
-
import { scenarist } from
|
|
188
|
+
import express from "express";
|
|
189
|
+
import { scenarist } from "../test/setup";
|
|
176
190
|
|
|
177
191
|
const app = express();
|
|
178
192
|
app.use(express.json());
|
|
179
193
|
|
|
180
194
|
// Add Scenarist middleware (includes everything)
|
|
181
|
-
if (process.env.NODE_ENV ===
|
|
195
|
+
if (process.env.NODE_ENV === "test") {
|
|
182
196
|
app.use(scenarist.middleware);
|
|
183
197
|
}
|
|
184
198
|
|
|
185
199
|
// Your application routes
|
|
186
|
-
app.get(
|
|
187
|
-
const response = await fetch(
|
|
200
|
+
app.get("/api/user", async (req, res) => {
|
|
201
|
+
const response = await fetch("https://api.example.com/user");
|
|
188
202
|
const user = await response.json();
|
|
189
203
|
res.json(user);
|
|
190
204
|
});
|
|
@@ -196,29 +210,29 @@ export { app };
|
|
|
196
210
|
|
|
197
211
|
```typescript
|
|
198
212
|
// test/api.test.ts
|
|
199
|
-
import { describe, it, expect, beforeAll, afterAll } from
|
|
200
|
-
import request from
|
|
201
|
-
import { app } from
|
|
202
|
-
import { scenarist } from
|
|
213
|
+
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
|
214
|
+
import request from "supertest";
|
|
215
|
+
import { app } from "../src/app";
|
|
216
|
+
import { scenarist } from "./setup";
|
|
203
217
|
|
|
204
|
-
describe(
|
|
218
|
+
describe("User API", () => {
|
|
205
219
|
beforeAll(() => scenarist.start());
|
|
206
220
|
afterAll(() => scenarist.stop());
|
|
207
221
|
|
|
208
|
-
it(
|
|
222
|
+
it("should return admin user", async () => {
|
|
209
223
|
// Set scenario for this test
|
|
210
224
|
await request(app)
|
|
211
|
-
.post(
|
|
212
|
-
.set(
|
|
213
|
-
.send({ scenario:
|
|
225
|
+
.post("/__scenario__")
|
|
226
|
+
.set("x-scenarist-test-id", "admin-test")
|
|
227
|
+
.send({ scenario: "admin-user" });
|
|
214
228
|
|
|
215
229
|
// Make request - MSW intercepts automatically
|
|
216
230
|
const response = await request(app)
|
|
217
|
-
.get(
|
|
218
|
-
.set(
|
|
231
|
+
.get("/api/user")
|
|
232
|
+
.set("x-scenarist-test-id", "admin-test");
|
|
219
233
|
|
|
220
234
|
expect(response.status).toBe(200);
|
|
221
|
-
expect(response.body.role).toBe(
|
|
235
|
+
expect(response.body.role).toBe("admin");
|
|
222
236
|
});
|
|
223
237
|
});
|
|
224
238
|
```
|
|
@@ -230,40 +244,47 @@ describe('User API', () => {
|
|
|
230
244
|
Creates a Scenarist instance with everything wired automatically.
|
|
231
245
|
|
|
232
246
|
**Parameters:**
|
|
247
|
+
|
|
233
248
|
```typescript
|
|
234
249
|
type ExpressAdapterOptions<T extends ScenaristScenarios> = {
|
|
235
|
-
enabled: boolean;
|
|
236
|
-
scenarios: T;
|
|
237
|
-
strictMode?: boolean;
|
|
250
|
+
enabled: boolean; // Whether mocking is enabled
|
|
251
|
+
scenarios: T; // REQUIRED - scenarios object
|
|
252
|
+
strictMode?: boolean; // Return 501 for unmocked requests (default: false)
|
|
238
253
|
headers?: {
|
|
239
|
-
testId?: string;
|
|
254
|
+
testId?: string; // Header for test ID (default: 'x-scenarist-test-id')
|
|
240
255
|
};
|
|
241
256
|
endpoints?: {
|
|
242
|
-
setScenario?: string;
|
|
243
|
-
getScenario?: string;
|
|
257
|
+
setScenario?: string; // POST endpoint (default: '/__scenario__')
|
|
258
|
+
getScenario?: string; // GET endpoint (default: '/__scenario__')
|
|
244
259
|
};
|
|
245
|
-
defaultTestId?: string;
|
|
246
|
-
registry?: ScenarioRegistry;
|
|
247
|
-
store?: ScenarioStore;
|
|
260
|
+
defaultTestId?: string; // Default test ID (default: 'default-test')
|
|
261
|
+
registry?: ScenarioRegistry; // Custom registry (default: InMemoryScenarioRegistry)
|
|
262
|
+
store?: ScenarioStore; // Custom store (default: InMemoryScenarioStore)
|
|
248
263
|
};
|
|
249
264
|
```
|
|
250
265
|
|
|
251
266
|
**Returns:**
|
|
267
|
+
|
|
252
268
|
```typescript
|
|
253
269
|
type ExpressScenarist<T extends ScenaristScenarios> = {
|
|
254
|
-
config: ScenaristConfig;
|
|
255
|
-
middleware: Router;
|
|
256
|
-
switchScenario: (
|
|
270
|
+
config: ScenaristConfig; // Resolved configuration (endpoints, headers, etc.)
|
|
271
|
+
middleware: Router; // Express middleware (includes test ID extraction + scenario endpoints)
|
|
272
|
+
switchScenario: (
|
|
273
|
+
testId: string,
|
|
274
|
+
scenarioId: keyof T,
|
|
275
|
+
variant?: string,
|
|
276
|
+
) => ScenaristResult<void, Error>;
|
|
257
277
|
getActiveScenario: (testId: string) => ActiveScenario | undefined;
|
|
258
278
|
getScenarioById: (scenarioId: string) => ScenaristScenario | undefined;
|
|
259
279
|
listScenarios: () => ReadonlyArray<ScenaristScenario>;
|
|
260
280
|
clearScenario: (testId: string) => void;
|
|
261
|
-
start: () => void;
|
|
262
|
-
stop: () => Promise<void>;
|
|
281
|
+
start: () => void; // Start MSW server
|
|
282
|
+
stop: () => Promise<void>; // Stop MSW server
|
|
263
283
|
};
|
|
264
284
|
```
|
|
265
285
|
|
|
266
286
|
**Example:**
|
|
287
|
+
|
|
267
288
|
```typescript
|
|
268
289
|
const scenarios = {
|
|
269
290
|
default: defaultScenario,
|
|
@@ -290,6 +311,7 @@ The middleware automatically exposes these endpoints:
|
|
|
290
311
|
#### `POST /__scenario__` - Set Active Scenario
|
|
291
312
|
|
|
292
313
|
**Request:**
|
|
314
|
+
|
|
293
315
|
```typescript
|
|
294
316
|
{
|
|
295
317
|
scenario: string; // Scenario ID (required)
|
|
@@ -298,6 +320,7 @@ The middleware automatically exposes these endpoints:
|
|
|
298
320
|
```
|
|
299
321
|
|
|
300
322
|
**Response (200):**
|
|
323
|
+
|
|
301
324
|
```typescript
|
|
302
325
|
{
|
|
303
326
|
success: true;
|
|
@@ -308,16 +331,18 @@ The middleware automatically exposes these endpoints:
|
|
|
308
331
|
```
|
|
309
332
|
|
|
310
333
|
**Example:**
|
|
334
|
+
|
|
311
335
|
```typescript
|
|
312
336
|
await request(app)
|
|
313
|
-
.post(
|
|
314
|
-
.set(
|
|
315
|
-
.send({ scenario:
|
|
337
|
+
.post("/__scenario__")
|
|
338
|
+
.set("x-scenarist-test-id", "test-123")
|
|
339
|
+
.send({ scenario: "user-logged-in" });
|
|
316
340
|
```
|
|
317
341
|
|
|
318
342
|
#### `GET /__scenario__` - Get Active Scenario
|
|
319
343
|
|
|
320
344
|
**Response (200):**
|
|
345
|
+
|
|
321
346
|
```typescript
|
|
322
347
|
{
|
|
323
348
|
testId: string;
|
|
@@ -327,6 +352,7 @@ await request(app)
|
|
|
327
352
|
```
|
|
328
353
|
|
|
329
354
|
**Response (404) - No Active Scenario:**
|
|
355
|
+
|
|
330
356
|
```typescript
|
|
331
357
|
{
|
|
332
358
|
error: "No active scenario for this test ID";
|
|
@@ -335,22 +361,23 @@ await request(app)
|
|
|
335
361
|
```
|
|
336
362
|
|
|
337
363
|
**Example:**
|
|
364
|
+
|
|
338
365
|
```typescript
|
|
339
366
|
// After setting a scenario
|
|
340
367
|
const response = await request(app)
|
|
341
|
-
.get(
|
|
342
|
-
.set(
|
|
368
|
+
.get("/__scenario__")
|
|
369
|
+
.set("x-scenarist-test-id", "test-123");
|
|
343
370
|
|
|
344
371
|
expect(response.status).toBe(200);
|
|
345
|
-
expect(response.body.scenarioId).toBe(
|
|
372
|
+
expect(response.body.scenarioId).toBe("success");
|
|
346
373
|
|
|
347
374
|
// Before setting a scenario
|
|
348
375
|
const response2 = await request(app)
|
|
349
|
-
.get(
|
|
350
|
-
.set(
|
|
376
|
+
.get("/__scenario__")
|
|
377
|
+
.set("x-scenarist-test-id", "new-test");
|
|
351
378
|
|
|
352
379
|
expect(response2.status).toBe(404);
|
|
353
|
-
expect(response2.body.error).toBe(
|
|
380
|
+
expect(response2.body.error).toBe("No active scenario for this test ID");
|
|
354
381
|
```
|
|
355
382
|
|
|
356
383
|
## Core Capabilities
|
|
@@ -360,6 +387,7 @@ Scenarist provides 20+ powerful features for scenario-based testing. All capabil
|
|
|
360
387
|
### Request Matching (6 capabilities)
|
|
361
388
|
|
|
362
389
|
**Body matching (partial match)** - Match requests based on request body fields
|
|
390
|
+
|
|
363
391
|
```typescript
|
|
364
392
|
{
|
|
365
393
|
method: 'POST',
|
|
@@ -370,6 +398,7 @@ Scenarist provides 20+ powerful features for scenario-based testing. All capabil
|
|
|
370
398
|
```
|
|
371
399
|
|
|
372
400
|
**Header matching (exact match)** - Perfect for user tier testing
|
|
401
|
+
|
|
373
402
|
```typescript
|
|
374
403
|
{
|
|
375
404
|
method: 'GET',
|
|
@@ -380,6 +409,7 @@ Scenarist provides 20+ powerful features for scenario-based testing. All capabil
|
|
|
380
409
|
```
|
|
381
410
|
|
|
382
411
|
**Query parameter matching** - Different responses for filtered requests
|
|
412
|
+
|
|
383
413
|
```typescript
|
|
384
414
|
{
|
|
385
415
|
method: 'GET',
|
|
@@ -397,6 +427,7 @@ Scenarist provides 20+ powerful features for scenario-based testing. All capabil
|
|
|
397
427
|
|
|
398
428
|
**Single responses** - Return same response every time
|
|
399
429
|
**Response sequences (ordered)** - Return different response on each call
|
|
430
|
+
|
|
400
431
|
```typescript
|
|
401
432
|
{
|
|
402
433
|
method: 'GET',
|
|
@@ -419,6 +450,7 @@ Scenarist provides 20+ powerful features for scenario-based testing. All capabil
|
|
|
419
450
|
|
|
420
451
|
**State capture from requests** - Extract values from body/headers/query
|
|
421
452
|
**State injection via templates** - Inject captured state using `{{state.X}}`
|
|
453
|
+
|
|
422
454
|
```typescript
|
|
423
455
|
// Capture from POST
|
|
424
456
|
{
|
|
@@ -468,14 +500,10 @@ Each request can include an `x-scenarist-test-id` header. Scenarist uses this to
|
|
|
468
500
|
|
|
469
501
|
```typescript
|
|
470
502
|
// Test 1 uses scenario A
|
|
471
|
-
await request(app)
|
|
472
|
-
.get('/api/data')
|
|
473
|
-
.set('x-scenarist-test-id', 'test-1'); // Uses scenario A
|
|
503
|
+
await request(app).get("/api/data").set("x-scenarist-test-id", "test-1"); // Uses scenario A
|
|
474
504
|
|
|
475
505
|
// Test 2 uses scenario B (runs concurrently!)
|
|
476
|
-
await request(app)
|
|
477
|
-
.get('/api/data')
|
|
478
|
-
.set('x-scenarist-test-id', 'test-2'); // Uses scenario B
|
|
506
|
+
await request(app).get("/api/data").set("x-scenarist-test-id", "test-2"); // Uses scenario B
|
|
479
507
|
```
|
|
480
508
|
|
|
481
509
|
### Automatic Test ID Propagation
|
|
@@ -483,6 +511,7 @@ await request(app)
|
|
|
483
511
|
**Express advantage:** Unlike frameworks without middleware (like Next.js), Express uses **AsyncLocalStorage** to automatically propagate test IDs throughout the request lifecycle.
|
|
484
512
|
|
|
485
513
|
**What this means:**
|
|
514
|
+
|
|
486
515
|
- Middleware extracts test ID from `x-scenarist-test-id` header **once**
|
|
487
516
|
- Test ID stored in AsyncLocalStorage for the request duration
|
|
488
517
|
- MSW handlers automatically access test ID from AsyncLocalStorage
|
|
@@ -492,10 +521,10 @@ await request(app)
|
|
|
492
521
|
|
|
493
522
|
```typescript
|
|
494
523
|
// routes/products.ts
|
|
495
|
-
app.get(
|
|
524
|
+
app.get("/api/products", async (req, res) => {
|
|
496
525
|
// Test ID automatically available to MSW via AsyncLocalStorage
|
|
497
526
|
// No need to manually forward headers!
|
|
498
|
-
const response = await fetch(
|
|
527
|
+
const response = await fetch("http://external-api.com/products");
|
|
499
528
|
const products = await response.json();
|
|
500
529
|
res.json(products);
|
|
501
530
|
});
|
|
@@ -505,9 +534,9 @@ app.get('/api/products', async (req, res) => {
|
|
|
505
534
|
|
|
506
535
|
```typescript
|
|
507
536
|
// Next.js - MUST manually forward headers
|
|
508
|
-
const response = await fetch(
|
|
537
|
+
const response = await fetch("http://external-api.com/products", {
|
|
509
538
|
headers: {
|
|
510
|
-
...getScenaristHeaders(req,
|
|
539
|
+
...getScenaristHeaders(req), // Required!
|
|
511
540
|
},
|
|
512
541
|
});
|
|
513
542
|
```
|
|
@@ -516,11 +545,12 @@ const response = await fetch('http://external-api.com/products', {
|
|
|
516
545
|
|
|
517
546
|
```typescript
|
|
518
547
|
// Express - AsyncLocalStorage propagates automatically
|
|
519
|
-
const response = await fetch(
|
|
548
|
+
const response = await fetch("http://external-api.com/products");
|
|
520
549
|
// MSW handlers receive test ID from AsyncLocalStorage
|
|
521
550
|
```
|
|
522
551
|
|
|
523
552
|
**Why this works:**
|
|
553
|
+
|
|
524
554
|
- Express middleware runs before all routes
|
|
525
555
|
- Middleware extracts `x-scenarist-test-id` and stores in AsyncLocalStorage
|
|
526
556
|
- MSW dynamic handler reads from AsyncLocalStorage
|
|
@@ -531,6 +561,7 @@ const response = await fetch('http://external-api.com/products');
|
|
|
531
561
|
### Automatic MSW Integration
|
|
532
562
|
|
|
533
563
|
The `createScenarist()` function automatically:
|
|
564
|
+
|
|
534
565
|
1. Creates an MSW server with a dynamic handler
|
|
535
566
|
2. Wires test ID extraction from headers via AsyncLocalStorage
|
|
536
567
|
3. Sets up scenario control endpoints (POST/GET `/__scenario__`)
|
|
@@ -538,6 +569,7 @@ The `createScenarist()` function automatically:
|
|
|
538
569
|
5. Returns mocked responses based on the scenario
|
|
539
570
|
|
|
540
571
|
The `middleware` includes everything:
|
|
572
|
+
|
|
541
573
|
- Test ID extraction from `x-scenarist-test-id` header (stored in AsyncLocalStorage)
|
|
542
574
|
- Scenario control endpoints (`/__scenario__`)
|
|
543
575
|
- All wired together - just add `app.use(scenarist.middleware)`
|
|
@@ -550,20 +582,33 @@ If a mock isn't found in the active scenario, Scenarist automatically falls back
|
|
|
550
582
|
|
|
551
583
|
```typescript
|
|
552
584
|
const scenarios = {
|
|
553
|
-
default: {
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
585
|
+
default: {
|
|
586
|
+
// REQUIRED - must have 'default' key
|
|
587
|
+
id: "default",
|
|
588
|
+
name: "Default Happy Path",
|
|
589
|
+
description: "Base responses for all APIs",
|
|
557
590
|
mocks: [
|
|
558
|
-
{
|
|
559
|
-
|
|
591
|
+
{
|
|
592
|
+
method: "GET",
|
|
593
|
+
url: "*/api/users",
|
|
594
|
+
response: { status: 200, body: [] },
|
|
595
|
+
},
|
|
596
|
+
{
|
|
597
|
+
method: "GET",
|
|
598
|
+
url: "*/api/orders",
|
|
599
|
+
response: { status: 200, body: [] },
|
|
600
|
+
},
|
|
560
601
|
],
|
|
561
602
|
},
|
|
562
603
|
userError: {
|
|
563
|
-
id:
|
|
564
|
-
name:
|
|
604
|
+
id: "user-error",
|
|
605
|
+
name: "User API Error",
|
|
565
606
|
mocks: [
|
|
566
|
-
{
|
|
607
|
+
{
|
|
608
|
+
method: "GET",
|
|
609
|
+
url: "*/api/users",
|
|
610
|
+
response: { status: 500, body: { error: "Server error" } },
|
|
611
|
+
},
|
|
567
612
|
// Orders endpoint falls back to default scenario
|
|
568
613
|
],
|
|
569
614
|
},
|
|
@@ -571,7 +616,7 @@ const scenarios = {
|
|
|
571
616
|
|
|
572
617
|
const scenarist = createScenarist({
|
|
573
618
|
enabled: true,
|
|
574
|
-
scenarios,
|
|
619
|
+
scenarios, // 'default' key is validated at runtime
|
|
575
620
|
});
|
|
576
621
|
```
|
|
577
622
|
|
|
@@ -581,7 +626,7 @@ The new API provides full type safety with TypeScript autocomplete for scenario
|
|
|
581
626
|
|
|
582
627
|
```typescript
|
|
583
628
|
// scenarios.ts - define scenarios with type constraint
|
|
584
|
-
import type { ScenaristScenarios } from
|
|
629
|
+
import type { ScenaristScenarios } from "@scenarist/express-adapter";
|
|
585
630
|
|
|
586
631
|
export const scenarios = {
|
|
587
632
|
default: defaultScenario,
|
|
@@ -592,7 +637,7 @@ export const scenarios = {
|
|
|
592
637
|
} as const satisfies ScenaristScenarios;
|
|
593
638
|
|
|
594
639
|
// setup.ts - create scenarist with type parameter
|
|
595
|
-
import { scenarios } from
|
|
640
|
+
import { scenarios } from "./scenarios";
|
|
596
641
|
|
|
597
642
|
export const scenarist = createScenarist({
|
|
598
643
|
enabled: true,
|
|
@@ -600,16 +645,17 @@ export const scenarist = createScenarist({
|
|
|
600
645
|
});
|
|
601
646
|
|
|
602
647
|
// test.ts - type-safe scenario switching
|
|
603
|
-
scenarist.switchScenario(
|
|
604
|
-
scenarist.switchScenario(
|
|
648
|
+
scenarist.switchScenario("test-123", "success"); // ✅ Autocomplete works!
|
|
649
|
+
scenarist.switchScenario("test-123", "invalid-name"); // ❌ TypeScript error!
|
|
605
650
|
|
|
606
651
|
await request(app)
|
|
607
652
|
.post(scenarist.config.endpoints.setScenario)
|
|
608
|
-
.set(SCENARIST_TEST_ID_HEADER,
|
|
609
|
-
.send({ scenario:
|
|
653
|
+
.set(SCENARIST_TEST_ID_HEADER, "test-123")
|
|
654
|
+
.send({ scenario: "success" }); // ✅ Type-safe!
|
|
610
655
|
```
|
|
611
656
|
|
|
612
657
|
**Benefits:**
|
|
658
|
+
|
|
613
659
|
- ✅ Autocomplete for scenario IDs in your editor
|
|
614
660
|
- ✅ Refactor-safe (rename propagates everywhere)
|
|
615
661
|
- ✅ Compile-time errors for typos
|
|
@@ -623,30 +669,35 @@ Create helper functions to reduce boilerplate:
|
|
|
623
669
|
|
|
624
670
|
```typescript
|
|
625
671
|
// test/helpers.ts
|
|
626
|
-
import request from
|
|
627
|
-
import { app } from
|
|
628
|
-
|
|
629
|
-
export const setScenario = async (
|
|
672
|
+
import request from "supertest";
|
|
673
|
+
import { app } from "../src/app";
|
|
674
|
+
|
|
675
|
+
export const setScenario = async (
|
|
676
|
+
testId: string,
|
|
677
|
+
scenario: string,
|
|
678
|
+
variant?: string,
|
|
679
|
+
) => {
|
|
630
680
|
await request(app)
|
|
631
|
-
.post(
|
|
632
|
-
.set(
|
|
681
|
+
.post("/__scenario__")
|
|
682
|
+
.set("x-scenarist-test-id", testId)
|
|
633
683
|
.send({ scenario, variant });
|
|
634
684
|
};
|
|
635
685
|
|
|
636
686
|
export const makeRequest = (testId: string) => {
|
|
637
|
-
return request(app).set(
|
|
687
|
+
return request(app).set("x-scenarist-test-id", testId);
|
|
638
688
|
};
|
|
639
689
|
```
|
|
640
690
|
|
|
641
691
|
**Usage:**
|
|
692
|
+
|
|
642
693
|
```typescript
|
|
643
|
-
import { setScenario, makeRequest } from
|
|
694
|
+
import { setScenario, makeRequest } from "./helpers";
|
|
644
695
|
|
|
645
|
-
test(
|
|
646
|
-
const testId =
|
|
647
|
-
await setScenario(testId,
|
|
696
|
+
test("payment flow", async () => {
|
|
697
|
+
const testId = "payment-test";
|
|
698
|
+
await setScenario(testId, "payment-success");
|
|
648
699
|
|
|
649
|
-
const response = await makeRequest(testId).post(
|
|
700
|
+
const response = await makeRequest(testId).post("/api/charge");
|
|
650
701
|
expect(response.status).toBe(200);
|
|
651
702
|
});
|
|
652
703
|
```
|
|
@@ -656,18 +707,18 @@ test('payment flow', async () => {
|
|
|
656
707
|
Generate unique test IDs automatically:
|
|
657
708
|
|
|
658
709
|
```typescript
|
|
659
|
-
import { randomUUID } from
|
|
710
|
+
import { randomUUID } from "crypto";
|
|
660
711
|
|
|
661
|
-
describe(
|
|
712
|
+
describe("API Tests", () => {
|
|
662
713
|
let testId: string;
|
|
663
714
|
|
|
664
715
|
beforeEach(() => {
|
|
665
716
|
testId = randomUUID();
|
|
666
717
|
});
|
|
667
718
|
|
|
668
|
-
it(
|
|
669
|
-
await setScenario(testId,
|
|
670
|
-
const response = await makeRequest(testId).post(
|
|
719
|
+
it("should process payment", async () => {
|
|
720
|
+
await setScenario(testId, "payment-success");
|
|
721
|
+
const response = await makeRequest(testId).post("/api/charge");
|
|
671
722
|
expect(response.status).toBe(200);
|
|
672
723
|
});
|
|
673
724
|
});
|
|
@@ -679,7 +730,8 @@ Enable scenario switching during development:
|
|
|
679
730
|
|
|
680
731
|
```typescript
|
|
681
732
|
const scenarist = createScenarist({
|
|
682
|
-
enabled:
|
|
733
|
+
enabled:
|
|
734
|
+
process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test",
|
|
683
735
|
scenarios,
|
|
684
736
|
strictMode: false,
|
|
685
737
|
});
|
|
@@ -704,21 +756,22 @@ curl http://localhost:3000/__scenario__
|
|
|
704
756
|
```typescript
|
|
705
757
|
// Test-only
|
|
706
758
|
const scenarist = createScenarist({
|
|
707
|
-
enabled: process.env.NODE_ENV ===
|
|
759
|
+
enabled: process.env.NODE_ENV === "test",
|
|
708
760
|
scenarios,
|
|
709
761
|
strictMode: true, // Fail if any unmocked request
|
|
710
762
|
});
|
|
711
763
|
|
|
712
764
|
// Development and test
|
|
713
765
|
const scenarist = createScenarist({
|
|
714
|
-
enabled:
|
|
766
|
+
enabled:
|
|
767
|
+
process.env.NODE_ENV === "test" || process.env.NODE_ENV === "development",
|
|
715
768
|
scenarios,
|
|
716
769
|
strictMode: false, // Allow passthrough to real APIs
|
|
717
770
|
});
|
|
718
771
|
|
|
719
772
|
// Opt-in with environment variable
|
|
720
773
|
const scenarist = createScenarist({
|
|
721
|
-
enabled: process.env.ENABLE_MOCKING ===
|
|
774
|
+
enabled: process.env.ENABLE_MOCKING === "true",
|
|
722
775
|
scenarios,
|
|
723
776
|
strictMode: false,
|
|
724
777
|
});
|
|
@@ -731,11 +784,11 @@ const scenarist = createScenarist({
|
|
|
731
784
|
enabled: true,
|
|
732
785
|
scenarios,
|
|
733
786
|
headers: {
|
|
734
|
-
testId:
|
|
787
|
+
testId: "x-my-test-id",
|
|
735
788
|
},
|
|
736
789
|
endpoints: {
|
|
737
|
-
setScenario:
|
|
738
|
-
getScenario:
|
|
790
|
+
setScenario: "/api/scenarios/set",
|
|
791
|
+
getScenario: "/api/scenarios/active",
|
|
739
792
|
},
|
|
740
793
|
});
|
|
741
794
|
```
|
|
@@ -754,6 +807,7 @@ NODE_ENV=production node src/server.js
|
|
|
754
807
|
```
|
|
755
808
|
|
|
756
809
|
**How it works:**
|
|
810
|
+
|
|
757
811
|
1. `process.env.NODE_ENV === 'production'` evaluates to `true` at runtime
|
|
758
812
|
2. `createScenarist()` returns `undefined` without loading dependencies
|
|
759
813
|
3. MSW and all Scenarist code **never loads into memory**
|
|
@@ -773,8 +827,8 @@ Scenarist uses **conditional package.json exports** to provide a production-spec
|
|
|
773
827
|
{
|
|
774
828
|
"exports": {
|
|
775
829
|
".": {
|
|
776
|
-
"production": "./dist/setup/production.js",
|
|
777
|
-
"default": "./dist/index.js"
|
|
830
|
+
"production": "./dist/setup/production.js", // Zero imports
|
|
831
|
+
"default": "./dist/index.js" // Full implementation
|
|
778
832
|
}
|
|
779
833
|
}
|
|
780
834
|
}
|
|
@@ -783,11 +837,13 @@ Scenarist uses **conditional package.json exports** to provide a production-spec
|
|
|
783
837
|
The `"production"` condition is a **custom condition** (not a Node.js built-in like `"import"` or `"require"`). Bundlers must be explicitly configured to recognize it.
|
|
784
838
|
|
|
785
839
|
**Without configuration:**
|
|
840
|
+
|
|
786
841
|
- MSW code included in bundle (~320kb)
|
|
787
842
|
- Code never executes (safe)
|
|
788
843
|
- Wastes bandwidth
|
|
789
844
|
|
|
790
845
|
**With configuration:**
|
|
846
|
+
|
|
791
847
|
- MSW code completely eliminated
|
|
792
848
|
- Bundle size reduced by ~52% (618kb → 298kb)
|
|
793
849
|
- Optimal production deployment
|
|
@@ -813,15 +869,15 @@ Add `conditionNames` to resolve configuration:
|
|
|
813
869
|
```javascript
|
|
814
870
|
// webpack.config.js
|
|
815
871
|
module.exports = {
|
|
816
|
-
mode:
|
|
872
|
+
mode: "production",
|
|
817
873
|
resolve: {
|
|
818
|
-
conditionNames: [
|
|
874
|
+
conditionNames: ["production", "import", "require"],
|
|
819
875
|
},
|
|
820
876
|
plugins: [
|
|
821
877
|
new webpack.DefinePlugin({
|
|
822
|
-
|
|
823
|
-
})
|
|
824
|
-
]
|
|
878
|
+
"process.env.NODE_ENV": JSON.stringify("production"),
|
|
879
|
+
}),
|
|
880
|
+
],
|
|
825
881
|
};
|
|
826
882
|
```
|
|
827
883
|
|
|
@@ -833,11 +889,11 @@ Add `conditions` to resolve configuration:
|
|
|
833
889
|
// vite.config.js
|
|
834
890
|
export default {
|
|
835
891
|
resolve: {
|
|
836
|
-
conditions: [
|
|
892
|
+
conditions: ["production"],
|
|
837
893
|
},
|
|
838
894
|
define: {
|
|
839
|
-
|
|
840
|
-
}
|
|
895
|
+
"process.env.NODE_ENV": JSON.stringify("production"),
|
|
896
|
+
},
|
|
841
897
|
};
|
|
842
898
|
```
|
|
843
899
|
|
|
@@ -847,19 +903,19 @@ Add `exportConditions` to node-resolve plugin:
|
|
|
847
903
|
|
|
848
904
|
```javascript
|
|
849
905
|
// rollup.config.js
|
|
850
|
-
import resolve from
|
|
851
|
-
import replace from
|
|
906
|
+
import resolve from "@rollup/plugin-node-resolve";
|
|
907
|
+
import replace from "@rollup/plugin-replace";
|
|
852
908
|
|
|
853
909
|
export default {
|
|
854
910
|
plugins: [
|
|
855
911
|
resolve({
|
|
856
|
-
exportConditions: [
|
|
912
|
+
exportConditions: ["production"],
|
|
857
913
|
}),
|
|
858
914
|
replace({
|
|
859
|
-
|
|
860
|
-
preventAssignment: true
|
|
861
|
-
})
|
|
862
|
-
]
|
|
915
|
+
"process.env.NODE_ENV": JSON.stringify("production"),
|
|
916
|
+
preventAssignment: true,
|
|
917
|
+
}),
|
|
918
|
+
],
|
|
863
919
|
};
|
|
864
920
|
```
|
|
865
921
|
|
|
@@ -880,11 +936,13 @@ The Express example app includes a verification script you can adapt:
|
|
|
880
936
|
```
|
|
881
937
|
|
|
882
938
|
**Run verification:**
|
|
939
|
+
|
|
883
940
|
```bash
|
|
884
941
|
pnpm verify:treeshaking
|
|
885
942
|
```
|
|
886
943
|
|
|
887
944
|
**Success output:**
|
|
945
|
+
|
|
888
946
|
```
|
|
889
947
|
dist/server.js 298.4kb
|
|
890
948
|
|
|
@@ -896,24 +954,27 @@ The script checks that MSW-specific implementation patterns (`setupWorker`, `Htt
|
|
|
896
954
|
### Bundle Size Comparison
|
|
897
955
|
|
|
898
956
|
**Without tree-shaking configuration:**
|
|
957
|
+
|
|
899
958
|
- Bundle size: ~618kb
|
|
900
959
|
- Includes: Application + Zod + MSW + Scenarist
|
|
901
960
|
- Status: Code included but never executes
|
|
902
961
|
|
|
903
962
|
**With tree-shaking configuration:**
|
|
963
|
+
|
|
904
964
|
- Bundle size: ~298kb (52% reduction)
|
|
905
965
|
- Includes: Application + Zod only
|
|
906
966
|
- Status: MSW and Scenarist completely eliminated
|
|
907
967
|
|
|
908
968
|
### Trade-Offs
|
|
909
969
|
|
|
910
|
-
| Deployment Type
|
|
911
|
-
|
|
912
|
-
| **Unbundled** (standard Express) | ✅ None
|
|
913
|
-
| **Bundled** without config
|
|
914
|
-
| **Bundled** with config
|
|
970
|
+
| Deployment Type | Configuration Required | Tree-Shaking | Bundle Impact |
|
|
971
|
+
| -------------------------------- | ---------------------- | ------------ | -------------------------- |
|
|
972
|
+
| **Unbundled** (standard Express) | ✅ None | ✅ Automatic | ✅ Zero (code never loads) |
|
|
973
|
+
| **Bundled** without config | ❌ None | ❌ Partial | ⚠️ ~320kb dead code |
|
|
974
|
+
| **Bundled** with config | ✅ One line | ✅ Complete | ✅ Zero (eliminated) |
|
|
915
975
|
|
|
916
976
|
**Recommendation:**
|
|
977
|
+
|
|
917
978
|
- If you're deploying unbundled code: No action needed ✅
|
|
918
979
|
- If you're bundling: Add the one-line bundler configuration for optimal bundle size
|
|
919
980
|
|
|
@@ -926,8 +987,8 @@ The script checks that MSW-specific implementation patterns (`setupWorker`, `Htt
|
|
|
926
987
|
**Solution:** Ensure you've called `scenarist.start()` before tests and `scenarist.stop()` after:
|
|
927
988
|
|
|
928
989
|
```typescript
|
|
929
|
-
beforeAll(() => scenarist.start());
|
|
930
|
-
afterAll(() => scenarist.stop());
|
|
990
|
+
beforeAll(() => scenarist.start()); // Starts MSW server
|
|
991
|
+
afterAll(() => scenarist.stop()); // Stops MSW server
|
|
931
992
|
```
|
|
932
993
|
|
|
933
994
|
### Tests see each other's scenarios
|
|
@@ -938,14 +999,14 @@ afterAll(() => scenarist.stop()); // Stops MSW server
|
|
|
938
999
|
|
|
939
1000
|
```typescript
|
|
940
1001
|
// ❌ Wrong - missing header on second request
|
|
941
|
-
await setScenario(
|
|
942
|
-
const response = await request(app).get(
|
|
1002
|
+
await setScenario("test-1", "my-scenario");
|
|
1003
|
+
const response = await request(app).get("/api/data"); // No test ID!
|
|
943
1004
|
|
|
944
1005
|
// ✅ Correct - header on all requests
|
|
945
|
-
await setScenario(
|
|
1006
|
+
await setScenario("test-1", "my-scenario");
|
|
946
1007
|
const response = await request(app)
|
|
947
|
-
.get(
|
|
948
|
-
.set(
|
|
1008
|
+
.get("/api/data")
|
|
1009
|
+
.set("x-scenarist-test-id", "test-1");
|
|
949
1010
|
```
|
|
950
1011
|
|
|
951
1012
|
### Scenario not found error
|
|
@@ -957,7 +1018,7 @@ const response = await request(app)
|
|
|
957
1018
|
```typescript
|
|
958
1019
|
const scenarios = {
|
|
959
1020
|
default: defaultScenario,
|
|
960
|
-
myScenario: myScenario,
|
|
1021
|
+
myScenario: myScenario, // ✅ Registered
|
|
961
1022
|
} as const satisfies ScenaristScenarios;
|
|
962
1023
|
|
|
963
1024
|
const scenarist = createScenarist({
|
|
@@ -965,8 +1026,8 @@ const scenarist = createScenarist({
|
|
|
965
1026
|
scenarios,
|
|
966
1027
|
});
|
|
967
1028
|
|
|
968
|
-
await setScenario(
|
|
969
|
-
await setScenario(
|
|
1029
|
+
await setScenario("test-1", "myScenario"); // ✅ Works
|
|
1030
|
+
await setScenario("test-1", "unknown"); // ❌ Error: Scenario not found
|
|
970
1031
|
```
|
|
971
1032
|
|
|
972
1033
|
## TypeScript
|
|
@@ -974,12 +1035,13 @@ await setScenario('test-1', 'unknown'); // ❌ Error: Scenario not found
|
|
|
974
1035
|
This package is written in TypeScript and includes full type definitions.
|
|
975
1036
|
|
|
976
1037
|
**Exported Types:**
|
|
1038
|
+
|
|
977
1039
|
```typescript
|
|
978
1040
|
// Adapter-specific types
|
|
979
1041
|
import type {
|
|
980
1042
|
ExpressAdapterOptions,
|
|
981
1043
|
ExpressScenarist,
|
|
982
|
-
} from
|
|
1044
|
+
} from "@scenarist/express-adapter";
|
|
983
1045
|
|
|
984
1046
|
// Core types (re-exported for convenience)
|
|
985
1047
|
import type {
|
|
@@ -992,7 +1054,7 @@ import type {
|
|
|
992
1054
|
ScenaristScenarios,
|
|
993
1055
|
ScenaristConfig,
|
|
994
1056
|
ScenaristResult,
|
|
995
|
-
} from
|
|
1057
|
+
} from "@scenarist/express-adapter";
|
|
996
1058
|
```
|
|
997
1059
|
|
|
998
1060
|
**Note:** All core types are re-exported from `@scenarist/express-adapter`, so you only need one import path for all Scenarist types.
|
|
@@ -1008,6 +1070,7 @@ See the [**Express Example App**](../../apps/express-example) for a complete wor
|
|
|
1008
1070
|
- ✅ **Multiple scenarios** - Success, errors, timeouts, mixed results
|
|
1009
1071
|
|
|
1010
1072
|
The example includes:
|
|
1073
|
+
|
|
1011
1074
|
- Complete Express application with GitHub, Weather, and Stripe API integrations
|
|
1012
1075
|
- 7 different scenario definitions
|
|
1013
1076
|
- 20 passing E2E tests demonstrating all features
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { Request } from
|
|
2
|
-
import { type RequestContext, type ScenaristConfig } from
|
|
1
|
+
import type { Request } from "express";
|
|
2
|
+
import { type RequestContext, type ScenaristConfig } from "@scenarist/core";
|
|
3
3
|
export declare class ExpressRequestContext implements RequestContext {
|
|
4
4
|
private readonly req;
|
|
5
5
|
private readonly config;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"express-request-context.d.ts","sourceRoot":"","sources":["../../src/context/express-request-context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,
|
|
1
|
+
{"version":3,"file":"express-request-context.d.ts","sourceRoot":"","sources":["../../src/context/express-request-context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAEL,KAAK,cAAc,EACnB,KAAK,eAAe,EACrB,MAAM,iBAAiB,CAAC;AAEzB,qBAAa,qBAAsB,YAAW,cAAc;IAExD,OAAO,CAAC,QAAQ,CAAC,GAAG;IACpB,OAAO,CAAC,QAAQ,CAAC,MAAM;gBADN,GAAG,EAAE,OAAO,EACZ,MAAM,EAAE,eAAe;IAG1C,SAAS,IAAI,MAAM;IAcnB,UAAU,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC;IAI3D,WAAW,IAAI,MAAM;CAGtB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { SCENARIST_TEST_ID_HEADER } from
|
|
1
|
+
import { SCENARIST_TEST_ID_HEADER, } from "@scenarist/core";
|
|
2
2
|
export class ExpressRequestContext {
|
|
3
3
|
req;
|
|
4
4
|
config;
|
|
@@ -8,7 +8,7 @@ export class ExpressRequestContext {
|
|
|
8
8
|
}
|
|
9
9
|
getTestId() {
|
|
10
10
|
const header = this.req.headers[SCENARIST_TEST_ID_HEADER];
|
|
11
|
-
if (typeof header ===
|
|
11
|
+
if (typeof header === "string") {
|
|
12
12
|
return header;
|
|
13
13
|
}
|
|
14
14
|
if (Array.isArray(header) && header.length > 0 && header[0]) {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export { createScenarist } from
|
|
2
|
-
export type { ExpressAdapterOptions, ExpressScenarist, } from
|
|
3
|
-
export { ExpressRequestContext } from
|
|
4
|
-
export { createTestIdMiddleware, testIdStorage } from
|
|
5
|
-
export { createScenarioEndpoints } from
|
|
6
|
-
export { SCENARIST_TEST_ID_HEADER } from
|
|
7
|
-
export type { ScenaristScenario, ScenaristMock, ScenaristResponse, ScenaristSequence, ScenaristMatch, ScenaristCaptureConfig, ScenaristScenarios, ScenaristConfig, ScenaristResult, } from
|
|
1
|
+
export { createScenarist } from "./setup/setup-scenarist.js";
|
|
2
|
+
export type { ExpressAdapterOptions, ExpressScenarist, } from "./setup/setup-scenarist.js";
|
|
3
|
+
export { ExpressRequestContext } from "./context/express-request-context.js";
|
|
4
|
+
export { createTestIdMiddleware, testIdStorage, } from "./middleware/test-id-middleware.js";
|
|
5
|
+
export { createScenarioEndpoints } from "./endpoints/scenario-endpoints.js";
|
|
6
|
+
export { SCENARIST_TEST_ID_HEADER } from "@scenarist/core";
|
|
7
|
+
export type { ScenaristScenario, ScenaristMock, ScenaristResponse, ScenaristSequence, ScenaristMatch, ScenaristCaptureConfig, ScenaristScenarios, ScenaristConfig, ScenaristResult, } from "@scenarist/core";
|
|
8
8
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,YAAY,EACV,qBAAqB,EACrB,gBAAgB,GACjB,MAAM,4BAA4B,CAAC;AAGpC,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,YAAY,EACV,qBAAqB,EACrB,gBAAgB,GACjB,MAAM,4BAA4B,CAAC;AAGpC,OAAO,EAAE,qBAAqB,EAAE,MAAM,sCAAsC,CAAC;AAC7E,OAAO,EACL,sBAAsB,EACtB,aAAa,GACd,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,uBAAuB,EAAE,MAAM,mCAAmC,CAAC;AAG5E,OAAO,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAC;AAC3D,YAAY,EACV,iBAAiB,EACjB,aAAa,EACb,iBAAiB,EACjB,iBAAiB,EACjB,cAAc,EACd,sBAAsB,EACtB,kBAAkB,EAClB,eAAe,EACf,eAAe,GAChB,MAAM,iBAAiB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// Primary API - batteries included setup
|
|
2
|
-
export { createScenarist } from
|
|
2
|
+
export { createScenarist } from "./setup/setup-scenarist.js";
|
|
3
3
|
// Low-level API - for advanced users who need custom wiring
|
|
4
|
-
export { ExpressRequestContext } from
|
|
5
|
-
export { createTestIdMiddleware, testIdStorage } from
|
|
6
|
-
export { createScenarioEndpoints } from
|
|
4
|
+
export { ExpressRequestContext } from "./context/express-request-context.js";
|
|
5
|
+
export { createTestIdMiddleware, testIdStorage, } from "./middleware/test-id-middleware.js";
|
|
6
|
+
export { createScenarioEndpoints } from "./endpoints/scenario-endpoints.js";
|
|
7
7
|
// Re-export core types and constants for user convenience (users should only install this adapter)
|
|
8
|
-
export { SCENARIST_TEST_ID_HEADER } from
|
|
8
|
+
export { SCENARIST_TEST_ID_HEADER } from "@scenarist/core";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { AsyncLocalStorage } from
|
|
2
|
-
import type { RequestHandler } from
|
|
3
|
-
import type { ScenaristConfig } from
|
|
1
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
2
|
+
import type { RequestHandler } from "express";
|
|
3
|
+
import type { ScenaristConfig } from "@scenarist/core";
|
|
4
4
|
export declare const testIdStorage: AsyncLocalStorage<string>;
|
|
5
5
|
export declare const createTestIdMiddleware: (config: ScenaristConfig) => RequestHandler;
|
|
6
6
|
//# sourceMappingURL=test-id-middleware.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"test-id-middleware.d.ts","sourceRoot":"","sources":["../../src/middleware/test-id-middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAC9C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAGvD,eAAO,MAAM,aAAa,2BAAkC,CAAC;AAE7D,eAAO,MAAM,sBAAsB,
|
|
1
|
+
{"version":3,"file":"test-id-middleware.d.ts","sourceRoot":"","sources":["../../src/middleware/test-id-middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAC9C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAGvD,eAAO,MAAM,aAAa,2BAAkC,CAAC;AAE7D,eAAO,MAAM,sBAAsB,GACjC,QAAQ,eAAe,KACtB,cASF,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { AsyncLocalStorage } from
|
|
2
|
-
import { ExpressRequestContext } from
|
|
1
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
2
|
+
import { ExpressRequestContext } from "../context/express-request-context.js";
|
|
3
3
|
export const testIdStorage = new AsyncLocalStorage();
|
|
4
4
|
export const createTestIdMiddleware = (config) => {
|
|
5
5
|
return (req, _res, next) => {
|
package/dist/setup/impl.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Router } from
|
|
2
|
-
import { type BaseAdapterOptions, type ScenaristAdapter, type ScenaristScenarios } from
|
|
1
|
+
import { Router } from "express";
|
|
2
|
+
import { type BaseAdapterOptions, type ScenaristAdapter, type ScenaristScenarios } from "@scenarist/core";
|
|
3
3
|
/**
|
|
4
4
|
* Express-specific adapter options.
|
|
5
5
|
*
|
package/dist/setup/impl.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"impl.d.ts","sourceRoot":"","sources":["../../src/setup/impl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAEjC,OAAO,EAQL,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EACxB,MAAM,iBAAiB,CAAC;AAMzB;;;;;;GAMG;AACH,MAAM,MAAM,qBAAqB,
|
|
1
|
+
{"version":3,"file":"impl.d.ts","sourceRoot":"","sources":["../../src/setup/impl.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAEjC,OAAO,EAQL,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EACxB,MAAM,iBAAiB,CAAC;AAMzB;;;;;;GAMG;AACH,MAAM,MAAM,qBAAqB,CAC/B,CAAC,SAAS,kBAAkB,GAAG,kBAAkB,IAC/C,kBAAkB,CAAC,CAAC,CAAC,CAAC;AAE1B;;;;;;GAMG;AACH,MAAM,MAAM,gBAAgB,CAC1B,CAAC,SAAS,kBAAkB,GAAG,kBAAkB,IAC/C,gBAAgB,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;AAEhC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,eAAO,MAAM,mBAAmB,GAAI,CAAC,SAAS,kBAAkB,EAC9D,SAAS,qBAAqB,CAAC,CAAC,CAAC,KAChC,gBAAgB,CAAC,CAAC,CAmDpB,CAAC"}
|
package/dist/setup/impl.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { Router } from
|
|
2
|
-
import { setupServer } from
|
|
3
|
-
import { buildConfig, createScenarioManager, createResponseSelector, InMemoryScenarioRegistry, InMemoryScenarioStore, createInMemorySequenceTracker, createInMemoryStateManager, } from
|
|
4
|
-
import { createDynamicHandler } from
|
|
5
|
-
import { testIdStorage } from
|
|
6
|
-
import { createTestIdMiddleware } from
|
|
7
|
-
import { createScenarioEndpoints } from
|
|
1
|
+
import { Router } from "express";
|
|
2
|
+
import { setupServer } from "msw/node";
|
|
3
|
+
import { buildConfig, createScenarioManager, createResponseSelector, InMemoryScenarioRegistry, InMemoryScenarioStore, createInMemorySequenceTracker, createInMemoryStateManager, } from "@scenarist/core";
|
|
4
|
+
import { createDynamicHandler } from "@scenarist/msw-adapter";
|
|
5
|
+
import { testIdStorage } from "../middleware/test-id-middleware.js";
|
|
6
|
+
import { createTestIdMiddleware } from "../middleware/test-id-middleware.js";
|
|
7
|
+
import { createScenarioEndpoints } from "../endpoints/scenario-endpoints.js";
|
|
8
8
|
/**
|
|
9
9
|
* Create a Scenarist instance for Express.
|
|
10
10
|
*
|
|
@@ -41,12 +41,20 @@ export const createScenaristImpl = (options) => {
|
|
|
41
41
|
const store = options.store ?? new InMemoryScenarioStore();
|
|
42
42
|
const stateManager = createInMemoryStateManager();
|
|
43
43
|
const sequenceTracker = createInMemorySequenceTracker();
|
|
44
|
-
const manager = createScenarioManager({
|
|
44
|
+
const manager = createScenarioManager({
|
|
45
|
+
registry,
|
|
46
|
+
store,
|
|
47
|
+
stateManager,
|
|
48
|
+
sequenceTracker,
|
|
49
|
+
});
|
|
45
50
|
// Register all scenarios upfront from the scenarios object
|
|
46
51
|
Object.values(options.scenarios).forEach((scenario) => {
|
|
47
52
|
manager.registerScenario(scenario);
|
|
48
53
|
});
|
|
49
|
-
const responseSelector = createResponseSelector({
|
|
54
|
+
const responseSelector = createResponseSelector({
|
|
55
|
+
sequenceTracker,
|
|
56
|
+
stateManager,
|
|
57
|
+
});
|
|
50
58
|
const handler = createDynamicHandler({
|
|
51
59
|
getTestId: (_request) => testIdStorage.getStore() ?? config.defaultTestId,
|
|
52
60
|
getActiveScenario: (testId) => manager.getActiveScenario(testId),
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { ScenaristScenarios } from
|
|
2
|
-
export type { ExpressAdapterOptions, ExpressScenarist } from
|
|
1
|
+
import type { ScenaristScenarios } from "@scenarist/core";
|
|
2
|
+
export type { ExpressAdapterOptions, ExpressScenarist } from "./impl.js";
|
|
3
3
|
/**
|
|
4
4
|
* Production-only entry point that returns undefined without loading any dependencies.
|
|
5
5
|
* This file has ZERO imports to guarantee tree-shaking.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { ScenaristScenarios } from
|
|
2
|
-
export type { ExpressAdapterOptions, ExpressScenarist } from
|
|
1
|
+
import type { ScenaristScenarios } from "@scenarist/core";
|
|
2
|
+
export type { ExpressAdapterOptions, ExpressScenarist } from "./impl.js";
|
|
3
3
|
/**
|
|
4
4
|
* Create a Scenarist instance for Express.
|
|
5
5
|
*
|
|
@@ -26,10 +26,10 @@
|
|
|
26
26
|
export const createScenarist = async (options) => {
|
|
27
27
|
// In production, return undefined without loading impl.js
|
|
28
28
|
// Dynamic import below is never executed, enabling tree-shaking
|
|
29
|
-
if (process.env.NODE_ENV ===
|
|
29
|
+
if (process.env.NODE_ENV === "production") {
|
|
30
30
|
return undefined;
|
|
31
31
|
}
|
|
32
32
|
// In non-production, dynamically import and create instance
|
|
33
|
-
const { createScenaristImpl } = await import(
|
|
33
|
+
const { createScenaristImpl } = await import("./impl.js");
|
|
34
34
|
return createScenaristImpl(options);
|
|
35
35
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@scenarist/express-adapter",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.8",
|
|
4
4
|
"description": "Express middleware adapter for Scenarist",
|
|
5
5
|
"author": "Paul Hammond (citypaul) <paul@packsoftware.co.uk>",
|
|
6
6
|
"license": "MIT",
|
|
@@ -48,8 +48,8 @@
|
|
|
48
48
|
],
|
|
49
49
|
"dependencies": {
|
|
50
50
|
"zod": "^4.1.13",
|
|
51
|
-
"@scenarist/
|
|
52
|
-
"@scenarist/
|
|
51
|
+
"@scenarist/core": "0.1.2",
|
|
52
|
+
"@scenarist/msw-adapter": "0.1.2"
|
|
53
53
|
},
|
|
54
54
|
"peerDependencies": {
|
|
55
55
|
"express": "^4.18.0 || ^5.0.0",
|