@schmock/core 1.0.4 → 1.2.1

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.
@@ -1,12 +1,31 @@
1
1
  import { describeFeature, loadFeature } from "@amiceli/vitest-cucumber";
2
2
  import { expect } from "vitest";
3
3
  import { schmock } from "../index";
4
- import type { MockInstance } from "../types";
4
+ import type { CallableMockInstance } from "../types";
5
+
6
+ interface CartItem {
7
+ id: number;
8
+ name: string;
9
+ price: number;
10
+ quantity: number;
11
+ }
12
+
13
+ interface UserRecord {
14
+ username: string;
15
+ password: string;
16
+ profile: { name: string; role: string };
17
+ }
18
+
19
+ interface SessionRecord {
20
+ user: string;
21
+ profile: { name: string; role: string };
22
+ loginTime: string;
23
+ }
5
24
 
6
25
  const feature = await loadFeature("../../features/stateful-workflows.feature");
7
26
 
8
27
  describeFeature(feature, ({ Scenario }) => {
9
- let mock: MockInstance<any>;
28
+ let mock: CallableMockInstance;
10
29
  let response: any;
11
30
  let sessionToken: string;
12
31
  let addedItemIds: number[] = [];
@@ -14,73 +33,65 @@ describeFeature(feature, ({ Scenario }) => {
14
33
  Scenario("Shopping cart workflow", ({ Given, When, Then, And }) => {
15
34
  addedItemIds = [];
16
35
 
17
- Given("I create a stateful shopping cart mock:", (_, docString: string) => {
18
- // Create stateful shopping cart mock with new callable API
19
- const sharedState = { items: [], total: 0 };
20
- mock = schmock({ state: sharedState });
21
-
22
- mock('GET /cart', ({ state }) => ({
23
- items: state.items,
24
- total: state.total,
25
- count: state.items.length
36
+ Given("I create a stateful shopping cart mock", () => {
37
+ const items: CartItem[] = [];
38
+ let total = 0;
39
+
40
+ mock = schmock();
41
+ mock("GET /cart", () => ({
42
+ items,
43
+ total,
44
+ count: items.length,
26
45
  }));
27
-
28
- mock('POST /cart/add', ({ state, body }) => {
29
- const item = {
30
- id: Date.now(),
31
- name: body.name,
32
- price: body.price,
33
- quantity: body.quantity || 1
46
+ mock("POST /cart/add", ({ body }) => {
47
+ const b = body as Record<string, unknown>;
48
+ const item: CartItem = {
49
+ id: Date.now(),
50
+ name: b.name as string,
51
+ price: b.price as number,
52
+ quantity: (b.quantity as number) || 1,
34
53
  };
35
-
36
- state.items.push(item);
37
- state.total += item.price * item.quantity;
38
-
54
+ items.push(item);
55
+ total += item.price * item.quantity;
39
56
  return {
40
- message: 'Item added to cart',
57
+ message: "Item added to cart",
41
58
  added: item,
42
59
  cart: {
43
- items: state.items,
44
- total: state.total,
45
- count: state.items.length
46
- }
60
+ items,
61
+ total,
62
+ count: items.length,
63
+ },
47
64
  };
48
65
  });
49
-
50
- mock('DELETE /cart/:id', ({ state, params }) => {
66
+ mock("DELETE /cart/:id", ({ params }) => {
51
67
  const itemId = parseInt(params.id);
52
- const itemIndex = state.items.findIndex(item => item.id === itemId);
53
-
68
+ const itemIndex = items.findIndex((item) => item.id === itemId);
54
69
  if (itemIndex === -1) {
55
- return [404, { error: 'Item not found in cart' }];
70
+ return [404, { error: "Item not found in cart" }];
56
71
  }
57
-
58
- const removedItem = state.items[itemIndex];
59
- state.total -= removedItem.price * removedItem.quantity;
60
- state.items.splice(itemIndex, 1);
61
-
72
+ const removedItem = items[itemIndex];
73
+ total -= removedItem.price * removedItem.quantity;
74
+ items.splice(itemIndex, 1);
62
75
  return {
63
- message: 'Item removed from cart',
76
+ message: "Item removed from cart",
64
77
  item: removedItem,
65
78
  cart: {
66
- items: state.items,
67
- total: state.total,
68
- count: state.items.length
69
- }
79
+ items,
80
+ total,
81
+ count: items.length,
82
+ },
70
83
  };
71
84
  });
72
-
73
- mock('POST /cart/clear', ({ state }) => {
74
- state.items = [];
75
- state.total = 0;
76
-
85
+ mock("POST /cart/clear", () => {
86
+ items.length = 0;
87
+ total = 0;
77
88
  return {
78
- message: 'Cart cleared',
89
+ message: "Cart cleared",
79
90
  cart: {
80
- items: state.items,
81
- total: state.total,
82
- count: state.items.length
83
- }
91
+ items,
92
+ total,
93
+ count: items.length,
94
+ },
84
95
  };
85
96
  });
86
97
  });
@@ -114,29 +125,34 @@ describeFeature(feature, ({ Scenario }) => {
114
125
 
115
126
  Then("the cart should contain {int} items", async (_, expectedCount: number) => {
116
127
  const cartResponse = await mock.handle("GET", "/cart");
117
- expect(cartResponse.body.count).toBe(expectedCount);
128
+ const body = cartResponse.body as { items: CartItem[]; total: number; count: number };
129
+ expect(body.count).toBe(expectedCount);
118
130
  });
119
131
 
120
132
  Then("the cart should contain {int} item", async (_, expectedCount: number) => {
121
133
  const cartResponse = await mock.handle("GET", "/cart");
122
- expect(cartResponse.body.count).toBe(expectedCount);
134
+ const body = cartResponse.body as { items: CartItem[]; total: number; count: number };
135
+ expect(body.count).toBe(expectedCount);
123
136
  });
124
137
 
125
138
  And("the initial cart total should be {string}", async (_, expectedTotalStr: string) => {
126
139
  const expectedTotal = parseFloat(expectedTotalStr);
127
140
  const cartResponse = await mock.handle("GET", "/cart");
128
- expect(cartResponse.body.total).toBe(expectedTotal);
141
+ const body = cartResponse.body as { items: CartItem[]; total: number; count: number };
142
+ expect(body.total).toBe(expectedTotal);
129
143
  });
130
144
 
131
145
  And("the final cart total should be {string}", async (_, expectedTotalStr: string) => {
132
146
  const expectedTotal = parseFloat(expectedTotalStr);
133
147
  const cartResponse = await mock.handle("GET", "/cart");
134
- expect(cartResponse.body.total).toBe(expectedTotal);
148
+ const body = cartResponse.body as { items: CartItem[]; total: number; count: number };
149
+ expect(body.total).toBe(expectedTotal);
135
150
  });
136
151
 
137
152
  When("I remove the first item from the cart", async () => {
138
153
  const cartResponse = await mock.handle("GET", "/cart");
139
- const firstItemId = cartResponse.body.items[0].id;
154
+ const body = cartResponse.body as { items: CartItem[]; total: number; count: number };
155
+ const firstItemId = body.items[0].id;
140
156
  response = await mock.handle("DELETE", `/cart/${firstItemId}`);
141
157
  });
142
158
  });
@@ -144,66 +160,54 @@ describeFeature(feature, ({ Scenario }) => {
144
160
  Scenario("User session simulation", ({ Given, When, Then, And }) => {
145
161
  sessionToken = "";
146
162
 
147
- Given("I create a session-based mock:", (_, docString: string) => {
148
- // Create session-based mock with new callable API
149
- const sharedState = {
150
- users: [
151
- { username: 'admin', password: 'secret', profile: { name: 'Admin User', role: 'administrator' } },
152
- { username: 'user1', password: 'pass123', profile: { name: 'Regular User', role: 'user' } }
153
- ],
154
- sessions: {}
155
- };
156
-
157
- mock = schmock({ state: sharedState });
158
-
159
- mock('POST /auth/login', ({ state, body }) => {
160
- const user = state.users.find(u => u.username === body.username && u.password === body.password);
161
-
163
+ Given("I create a session-based authentication mock", () => {
164
+ const users: UserRecord[] = [
165
+ { username: "admin", password: "secret", profile: { name: "Admin User", role: "administrator" } },
166
+ { username: "user1", password: "pass123", profile: { name: "Regular User", role: "user" } },
167
+ ];
168
+ const sessions: Record<string, SessionRecord> = {};
169
+
170
+ mock = schmock();
171
+ mock("POST /auth/login", ({ body }) => {
172
+ const b = body as Record<string, unknown>;
173
+ const user = users.find((u) => u.username === b.username && u.password === b.password);
162
174
  if (!user) {
163
- return [401, { error: 'Invalid credentials' }];
175
+ return [401, { error: "Invalid credentials" }];
164
176
  }
165
-
166
- const token = `token-${user.username}-${Date.now()}`;
167
- state.sessions[token] = {
177
+ const token = "token-" + user.username + "-" + Date.now();
178
+ sessions[token] = {
168
179
  user: user.username,
169
180
  profile: user.profile,
170
- loginTime: new Date().toISOString()
181
+ loginTime: new Date().toISOString(),
171
182
  };
172
-
173
183
  return {
174
- message: 'Login successful',
175
- token: token,
176
- user: user.profile
184
+ message: "Login successful",
185
+ token,
186
+ user: user.profile,
177
187
  };
178
188
  });
179
-
180
- mock('GET /profile', ({ state, headers }) => {
181
- const token = headers.authorization?.replace('Bearer ', '');
182
-
183
- if (!token || !state.sessions[token]) {
184
- return [401, { error: 'Unauthorized' }];
189
+ mock("GET /profile", ({ headers }) => {
190
+ const token = headers.authorization ? headers.authorization.replace("Bearer ", "") : "";
191
+ if (!token || !sessions[token]) {
192
+ return [401, { error: "Unauthorized" }];
185
193
  }
186
-
187
- const session = state.sessions[token];
194
+ const session = sessions[token];
188
195
  return {
189
196
  user: session.user,
190
197
  profile: session.profile,
191
198
  loginTime: session.loginTime,
192
199
  session: {
193
- active: true
194
- }
200
+ active: true,
201
+ },
195
202
  };
196
203
  });
197
-
198
- mock('POST /auth/logout', ({ state, headers }) => {
199
- const token = headers.authorization?.replace('Bearer ', '');
200
-
201
- if (!token || !state.sessions[token]) {
202
- return [401, { error: 'Unauthorized' }];
204
+ mock("POST /auth/logout", ({ headers }) => {
205
+ const token = headers.authorization ? headers.authorization.replace("Bearer ", "") : "";
206
+ if (!token || !sessions[token]) {
207
+ return [401, { error: "Unauthorized" }];
203
208
  }
204
-
205
- delete state.sessions[token];
206
- return { message: 'Logged out successfully' };
209
+ delete sessions[token];
210
+ return { message: "Logged out successfully" };
207
211
  });
208
212
  });
209
213
 
@@ -264,45 +268,37 @@ describeFeature(feature, ({ Scenario }) => {
264
268
  });
265
269
 
266
270
  Scenario("Multi-user state isolation", ({ Given, When, Then, And }) => {
267
- Given("I create a multi-user counter mock:", (_, docString: string) => {
268
- // Create multi-user counter mock with new callable API
269
- const sharedState = { counters: {} };
270
- mock = schmock({ state: sharedState });
271
-
272
- mock('POST /counter/:userId/increment', ({ state, params }) => {
271
+ Given("I create a multi-user counter mock", () => {
272
+ const counters: Record<string, number> = {};
273
+
274
+ mock = schmock();
275
+ mock("POST /counter/:userId/increment", ({ params }) => {
273
276
  const userId = params.userId;
274
-
275
- if (!state.counters[userId]) {
276
- state.counters[userId] = 0;
277
+ if (!counters[userId]) {
278
+ counters[userId] = 0;
277
279
  }
278
-
279
- state.counters[userId]++;
280
-
280
+ counters[userId]++;
281
281
  return {
282
- userId: userId,
283
- count: state.counters[userId],
284
- message: `Counter incremented for user ${userId}`
282
+ userId,
283
+ count: counters[userId],
284
+ message: "Counter incremented for user " + userId,
285
285
  };
286
286
  });
287
-
288
- mock('GET /counter/:userId', ({ state, params }) => {
287
+ mock("GET /counter/:userId", ({ params }) => {
289
288
  const userId = params.userId;
290
- const count = state.counters[userId] || 0;
291
-
289
+ const count = counters[userId] || 0;
292
290
  return {
293
- userId: userId,
294
- count: count
291
+ userId,
292
+ count,
295
293
  };
296
294
  });
297
-
298
- mock('GET /counters/summary', ({ state }) => {
299
- const totalCount = Object.values(state.counters).reduce((sum: number, count: number) => sum + count, 0);
300
- const userCount = Object.keys(state.counters).length;
301
-
295
+ mock("GET /counters/summary", () => {
296
+ const totalCount = Object.values(counters).reduce((sum, count) => sum + count, 0);
297
+ const userCount = Object.keys(counters).length;
302
298
  return {
303
299
  totalCounts: totalCount,
304
300
  totalUsers: userCount,
305
- counters: state.counters
301
+ counters,
306
302
  };
307
303
  });
308
304
  });
@@ -321,31 +317,37 @@ describeFeature(feature, ({ Scenario }) => {
321
317
 
322
318
  Then("{string}'s counter should be {int}", async (_, userId: string, expectedCount: number) => {
323
319
  const response = await mock.handle("GET", `/counter/${userId}`);
324
- expect(response.body.count).toBe(expectedCount);
320
+ const body = response.body as { userId: string; count: number };
321
+ expect(body.count).toBe(expectedCount);
325
322
  });
326
323
 
327
324
  And("{string}'s counter should be {int}", async (_, userId: string, expectedCount: number) => {
328
325
  const response = await mock.handle("GET", `/counter/${userId}`);
329
- expect(response.body.count).toBe(expectedCount);
326
+ const body = response.body as { userId: string; count: number };
327
+ expect(body.count).toBe(expectedCount);
330
328
  });
331
329
 
332
330
  And("the summary should show {int} total users", async (_, expectedUsers: number) => {
333
331
  const response = await mock.handle("GET", "/counters/summary");
334
- expect(response.body.totalUsers).toBe(expectedUsers);
332
+ const body = response.body as { totalCounts: number; totalUsers: number; counters: Record<string, number> };
333
+ expect(body.totalUsers).toBe(expectedUsers);
335
334
  });
336
335
 
337
336
  And("the summary should show total counts of {int}", async (_, expectedTotal: number) => {
338
337
  const response = await mock.handle("GET", "/counters/summary");
339
- expect(response.body.totalCounts).toBe(expectedTotal);
338
+ const body = response.body as { totalCounts: number; totalUsers: number; counters: Record<string, number> };
339
+ expect(body.totalCounts).toBe(expectedTotal);
340
340
  });
341
341
 
342
342
  And("each user's state should be independent", async () => {
343
343
  const aliceResponse = await mock.handle("GET", "/counter/alice");
344
344
  const bobResponse = await mock.handle("GET", "/counter/bob");
345
-
346
- expect(aliceResponse.body.count).toBe(3);
347
- expect(bobResponse.body.count).toBe(2);
348
- expect(aliceResponse.body.count).not.toBe(bobResponse.body.count);
345
+ const aliceBody = aliceResponse.body as { userId: string; count: number };
346
+ const bobBody = bobResponse.body as { userId: string; count: number };
347
+
348
+ expect(aliceBody.count).toBe(3);
349
+ expect(bobBody.count).toBe(2);
350
+ expect(aliceBody.count).not.toBe(bobBody.count);
349
351
  });
350
352
  });
351
- });
353
+ });