lambder 1.0.131 → 1.0.133

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.
@@ -0,0 +1,430 @@
1
+ # LambderMSW - Mock Service Worker Integration
2
+
3
+ LambderMSW provides seamless integration with [MSW (Mock Service Worker)](https://mswjs.io/) for testing your Lambder APIs. It allows you to mock API endpoints with full type safety when using TypeScript API contracts.
4
+
5
+ ## Installation
6
+
7
+ First, install MSW as a dev dependency:
8
+
9
+ ```bash
10
+ npm install msw --save-dev
11
+ # or
12
+ yarn add msw --dev
13
+ ```
14
+
15
+ ## Basic Setup
16
+
17
+ ```typescript
18
+ import { LambderMSW } from 'lambder';
19
+ import { setupServer } from 'msw/node';
20
+
21
+ // Create an MSW instance
22
+ const lambderMSW = new LambderMSW({
23
+ apiPath: '/secure', // Must match your Lambder backend apiPath
24
+ });
25
+
26
+ // Create mock handlers
27
+ const handlers = [
28
+ lambderMSW.mockApi('getUserById', async (payload) => {
29
+ return {
30
+ id: payload.userId,
31
+ name: 'John Doe',
32
+ email: 'john@example.com'
33
+ };
34
+ }),
35
+
36
+ lambderMSW.mockApi('createUser', async (payload) => {
37
+ return {
38
+ id: '123',
39
+ name: payload.name,
40
+ email: payload.email
41
+ };
42
+ })
43
+ ];
44
+
45
+ // Setup MSW server
46
+ const server = setupServer(...handlers);
47
+
48
+ // Start server before tests
49
+ beforeAll(() => server.listen());
50
+ afterEach(() => server.resetHandlers());
51
+ afterAll(() => server.close());
52
+ ```
53
+
54
+ ## Type-Safe Mocking
55
+
56
+ When using TypeScript API contracts, LambderMSW provides full type safety:
57
+
58
+ ```typescript
59
+ // shared/apiContract.ts
60
+ import type { ApiContract } from 'lambder';
61
+
62
+ export type MyApiContract = ApiContract<{
63
+ getUserById: {
64
+ input: { userId: string },
65
+ output: { id: string, name: string, email: string }
66
+ },
67
+ createUser: {
68
+ input: { name: string, email: string },
69
+ output: { id: string, name: string, email: string }
70
+ }
71
+ }>;
72
+
73
+ // test/setup.ts
74
+ import { LambderMSW } from 'lambder';
75
+ import type { MyApiContract } from '../shared/apiContract';
76
+
77
+ const lambderMSW = new LambderMSW<MyApiContract>({
78
+ apiPath: '/secure',
79
+ apiVersion: '1.0.0'
80
+ });
81
+
82
+ // Now mockApi is fully typed! ✨
83
+ const handler = lambderMSW.mockApi('getUserById', async (payload) => {
84
+ // payload is automatically typed as { userId: string }
85
+ // Return value is type-checked against output type
86
+ return {
87
+ id: payload.userId,
88
+ name: 'John Doe',
89
+ email: 'john@example.com'
90
+ };
91
+ });
92
+ ```
93
+
94
+ ## API Reference
95
+
96
+ ### `new LambderMSW(options)`
97
+
98
+ Creates a new LambderMSW instance.
99
+
100
+ **Parameters:**
101
+ - `apiPath` (string): The API endpoint path (must match your Lambder backend)
102
+ - `apiVersion` (string, optional): API version to include in responses
103
+
104
+ ### `mockApi(apiName, handler, options?)`
105
+
106
+ Mock an API endpoint with a custom handler.
107
+
108
+ **Parameters:**
109
+ - `apiName` (string): Name of the API to mock
110
+ - `handler` (function): Async or sync function that returns the mock payload
111
+ - Input: API payload from the request
112
+ - Output: The mocked response payload
113
+ - `options` (object, optional):
114
+ - `versionExpired` (boolean): Simulate version expired error
115
+ - `sessionExpired` (boolean): Simulate session expired error
116
+ - `notAuthorized` (boolean): Simulate not authorized error
117
+ - `message` (any): Custom message to include in response
118
+ - `errorMessage` (any): Error message to include in response
119
+ - `logList` (array): Array of log entries
120
+ - `delay` (number): Artificial delay in milliseconds to simulate network latency
121
+
122
+ **Returns:** MSW RequestHandler
123
+
124
+ **Example:**
125
+ ```typescript
126
+ lambderMSW.mockApi('getCompanyPage', async (payload) => {
127
+ return {
128
+ companyName: payload.companyName,
129
+ description: 'Mock company description',
130
+ employees: 100
131
+ };
132
+ }, {
133
+ delay: 500, // Simulate 500ms network delay
134
+ message: 'Data fetched successfully'
135
+ });
136
+ ```
137
+
138
+ ### `mockSessionExpired(apiName)`
139
+
140
+ Mock an API that returns a session expired error.
141
+
142
+ **Parameters:**
143
+ - `apiName` (string): Name of the API to mock
144
+
145
+ **Example:**
146
+ ```typescript
147
+ lambderMSW.mockSessionExpired('getProtectedData');
148
+ ```
149
+
150
+ ### `mockVersionExpired(apiName)`
151
+
152
+ Mock an API that returns a version expired error.
153
+
154
+ **Parameters:**
155
+ - `apiName` (string): Name of the API to mock
156
+
157
+ **Example:**
158
+ ```typescript
159
+ lambderMSW.mockVersionExpired('getUserProfile');
160
+ ```
161
+
162
+ ### `mockNotAuthorized(apiName)`
163
+
164
+ Mock an API that returns a not authorized error.
165
+
166
+ **Parameters:**
167
+ - `apiName` (string): Name of the API to mock
168
+
169
+ **Example:**
170
+ ```typescript
171
+ lambderMSW.mockNotAuthorized('deleteUser');
172
+ ```
173
+
174
+ ### `mockError(apiName, errorMessage)`
175
+
176
+ Mock an API that returns a custom error message.
177
+
178
+ **Parameters:**
179
+ - `apiName` (string): Name of the API to mock
180
+ - `errorMessage` (string): The error message to return
181
+
182
+ **Example:**
183
+ ```typescript
184
+ lambderMSW.mockError('submitOrder', 'Payment processing failed');
185
+ ```
186
+
187
+ ### `mockWithMessage(apiName, handler, message)`
188
+
189
+ Mock an API with a custom success message.
190
+
191
+ **Parameters:**
192
+ - `apiName` (string): Name of the API to mock
193
+ - `handler` (function): Handler function that returns the mock payload
194
+ - `message` (any): Custom message to include in response
195
+
196
+ **Example:**
197
+ ```typescript
198
+ lambderMSW.mockWithMessage('updateProfile', async (payload) => {
199
+ return { userId: payload.userId, updated: true };
200
+ }, 'Profile updated successfully');
201
+ ```
202
+
203
+ ## Complete Testing Example
204
+
205
+ ```typescript
206
+ // test/api.test.ts
207
+ import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest';
208
+ import { setupServer } from 'msw/node';
209
+ import { LambderMSW } from 'lambder';
210
+ import { LambderCaller } from 'lambder';
211
+ import type { MyApiContract } from '../shared/apiContract';
212
+
213
+ // Setup MSW
214
+ const lambderMSW = new LambderMSW<MyApiContract>({
215
+ apiPath: '/secure',
216
+ apiVersion: '1.0.0'
217
+ });
218
+
219
+ const handlers = [
220
+ lambderMSW.mockApi('getUserById', async (payload) => {
221
+ if (payload.userId === '123') {
222
+ return {
223
+ id: '123',
224
+ name: 'John Doe',
225
+ email: 'john@example.com'
226
+ };
227
+ }
228
+ return null;
229
+ }),
230
+
231
+ lambderMSW.mockApi('createUser', async (payload) => {
232
+ return {
233
+ id: Math.random().toString(),
234
+ name: payload.name,
235
+ email: payload.email
236
+ };
237
+ }, { delay: 100 }), // Simulate 100ms delay
238
+
239
+ lambderMSW.mockSessionExpired('getProtectedData'),
240
+
241
+ lambderMSW.mockError('failingApi', 'Something went wrong')
242
+ ];
243
+
244
+ const server = setupServer(...handlers);
245
+
246
+ beforeAll(() => server.listen());
247
+ afterEach(() => server.resetHandlers());
248
+ afterAll(() => server.close());
249
+
250
+ // Setup LambderCaller
251
+ const caller = new LambderCaller<MyApiContract>({
252
+ apiPath: '/secure',
253
+ isCorsEnabled: false
254
+ });
255
+
256
+ describe('User APIs', () => {
257
+ it('should fetch user by id', async () => {
258
+ const result = await caller.api('getUserById', { userId: '123' });
259
+
260
+ expect(result).toEqual({
261
+ id: '123',
262
+ name: 'John Doe',
263
+ email: 'john@example.com'
264
+ });
265
+ });
266
+
267
+ it('should create a new user', async () => {
268
+ const result = await caller.api('createUser', {
269
+ name: 'Jane Smith',
270
+ email: 'jane@example.com'
271
+ });
272
+
273
+ expect(result?.name).toBe('Jane Smith');
274
+ expect(result?.email).toBe('jane@example.com');
275
+ expect(result?.id).toBeDefined();
276
+ });
277
+
278
+ it('should handle session expired', async () => {
279
+ try {
280
+ await caller.api('getProtectedData', {});
281
+ // Should not reach here
282
+ expect(true).toBe(false);
283
+ } catch (error: any) {
284
+ expect(error.sessionExpired).toBe(true);
285
+ }
286
+ });
287
+
288
+ it('should handle errors', async () => {
289
+ try {
290
+ await caller.api('failingApi', {});
291
+ // Should not reach here
292
+ expect(true).toBe(false);
293
+ } catch (error: any) {
294
+ expect(error.errorMessage).toBe('Something went wrong');
295
+ }
296
+ });
297
+ });
298
+ ```
299
+
300
+ ## Browser Testing
301
+
302
+ LambderMSW also works in browser environments with MSW's browser integration:
303
+
304
+ ```typescript
305
+ // test/browser-setup.ts
306
+ import { setupWorker } from 'msw/browser';
307
+ import { LambderMSW } from 'lambder';
308
+ import type { MyApiContract } from '../shared/apiContract';
309
+
310
+ const lambderMSW = new LambderMSW<MyApiContract>({
311
+ apiPath: '/secure'
312
+ });
313
+
314
+ const handlers = [
315
+ lambderMSW.mockApi('getUserById', async (payload) => {
316
+ return {
317
+ id: payload.userId,
318
+ name: 'John Doe',
319
+ email: 'john@example.com'
320
+ };
321
+ })
322
+ ];
323
+
324
+ const worker = setupWorker(...handlers);
325
+
326
+ // Start the worker
327
+ worker.start();
328
+ ```
329
+
330
+ ## Advanced Usage
331
+
332
+ ### Dynamic Mock Responses
333
+
334
+ ```typescript
335
+ lambderMSW.mockApi('searchUsers', async (payload) => {
336
+ const { query, limit } = payload;
337
+
338
+ // Return different responses based on input
339
+ if (query === 'admin') {
340
+ return [{
341
+ id: '1',
342
+ name: 'Admin User',
343
+ role: 'admin'
344
+ }];
345
+ }
346
+
347
+ return Array.from({ length: limit }, (_, i) => ({
348
+ id: `${i}`,
349
+ name: `User ${i}`,
350
+ role: 'user'
351
+ }));
352
+ });
353
+ ```
354
+
355
+ ### Simulating Network Conditions
356
+
357
+ ```typescript
358
+ // Slow network
359
+ lambderMSW.mockApi('slowApi', async () => {
360
+ return { data: 'slow response' };
361
+ }, { delay: 3000 }); // 3 second delay
362
+
363
+ // Intermittent failures
364
+ let callCount = 0;
365
+ lambderMSW.mockApi('flakeyApi', async () => {
366
+ callCount++;
367
+ if (callCount % 3 === 0) {
368
+ throw new Error('Random failure');
369
+ }
370
+ return { success: true };
371
+ });
372
+ ```
373
+
374
+ ### Override Handlers Per Test
375
+
376
+ ```typescript
377
+ it('should handle specific user', async () => {
378
+ // Override the default handler for this test
379
+ server.use(
380
+ lambderMSW.mockApi('getUserById', async (payload) => {
381
+ return {
382
+ id: payload.userId,
383
+ name: 'Special User',
384
+ email: 'special@example.com'
385
+ };
386
+ })
387
+ );
388
+
389
+ const result = await caller.api('getUserById', { userId: '999' });
390
+ expect(result?.name).toBe('Special User');
391
+ });
392
+ ```
393
+
394
+ ## Benefits
395
+
396
+ ✅ **Type Safety** - Full TypeScript support with API contracts
397
+ ✅ **Simple API** - Intuitive methods matching Lambder's API structure
398
+ ✅ **Flexible** - Mock success, errors, delays, and custom responses
399
+ ✅ **Isolated** - Tests run without real backend dependencies
400
+ ✅ **Fast** - No network calls, instant test execution
401
+ ✅ **Realistic** - Simulate real-world scenarios (delays, errors, etc.)
402
+
403
+ ## Troubleshooting
404
+
405
+ ### MSW Not Found Error
406
+
407
+ If you see "MSW (Mock Service Worker) is required", make sure MSW is installed:
408
+
409
+ ```bash
410
+ npm install msw --save-dev
411
+ ```
412
+
413
+ ### Handler Not Matching
414
+
415
+ LambderMSW matches handlers based on the `apiName` in the request body. Make sure:
416
+ 1. Your `apiPath` matches between backend, frontend, and mocks
417
+ 2. The API name string matches exactly
418
+ 3. Handlers are registered before making requests
419
+
420
+ ### Console Warnings
421
+
422
+ LambderMSW logs matching information to console for debugging. To see these logs:
423
+ - Check browser console for "LambderMSW called for:" messages
424
+ - Verify "Matched!" appears when handler should execute
425
+
426
+ ## See Also
427
+
428
+ - [MSW Documentation](https://mswjs.io/)
429
+ - [Type-Safe Quick Start](./TYPE_SAFE_QUICK_START.md)
430
+ - [Lambder Main Documentation](../Readme.md)
@@ -156,6 +156,38 @@ lambder.addApi('anyApi', async (ctx, resolver) => {
156
156
 
157
157
  See [simplified-typed-api-example.ts](../examples/simplified-typed-api-example.ts) for a complete working example.
158
158
 
159
+ ## Testing Your Type-Safe APIs
160
+
161
+ LambderMSW provides full type safety for testing your APIs with MSW (Mock Service Worker):
162
+
163
+ ```typescript
164
+ import { LambderMSW } from 'lambder';
165
+ import { setupServer } from 'msw/node';
166
+ import type { MyApiContract } from './shared/apiContract';
167
+
168
+ // Create type-safe MSW instance
169
+ const lambderMSW = new LambderMSW<MyApiContract>({
170
+ apiPath: '/api'
171
+ });
172
+
173
+ // Mock with full type safety! ✨
174
+ const handlers = [
175
+ lambderMSW.mockApi('getUserById', async (payload) => {
176
+ // payload is typed as { userId: string }
177
+ // Return value is type-checked against output
178
+ return {
179
+ id: payload.userId,
180
+ name: 'John Doe',
181
+ email: 'john@example.com'
182
+ };
183
+ })
184
+ ];
185
+
186
+ const server = setupServer(...handlers);
187
+ ```
188
+
189
+ 📖 See [LAMBDER_MSW.md](./LAMBDER_MSW.md) for complete testing documentation.
190
+
159
191
  ## Key Points
160
192
 
161
193
  - **Contract is just a TypeScript type** - No runtime code!
@@ -165,3 +197,4 @@ See [simplified-typed-api-example.ts](../examples/simplified-typed-api-example.t
165
197
  - **Opt-in** - Use types when you want them
166
198
  - **Simple** - Just pass type to constructor
167
199
  - **Autocomplete** - IDE shows available APIs as you type
200
+ - **Testing support** - LambderMSW provides type-safe mocking