@nestia/e2e 7.0.0 → 7.0.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.
@@ -2,18 +2,57 @@ import { RandomGenerator } from "./RandomGenerator";
2
2
  import { json_equal_to } from "./internal/json_equal_to";
3
3
 
4
4
  /**
5
- * Test validator.
5
+ * A comprehensive collection of E2E validation utilities for testing
6
+ * applications.
6
7
  *
7
- * `TestValidator` is a collection gathering E2E validation functions.
8
+ * TestValidator provides type-safe validation functions for common testing
9
+ * scenarios including condition checking, equality validation, error testing,
10
+ * HTTP error validation, pagination testing, search functionality validation,
11
+ * and sorting validation.
12
+ *
13
+ * All functions follow a currying pattern to enable reusable test
14
+ * configurations and provide detailed error messages for debugging failed
15
+ * assertions.
8
16
  *
9
17
  * @author Jeongho Nam - https://github.com/samchon
18
+ * @example
19
+ * ```typescript
20
+ * // Basic condition testing
21
+ * TestValidator.predicate("user should be authenticated")(user.isAuthenticated);
22
+ *
23
+ * // Equality validation
24
+ * TestValidator.equals("API response should match expected")(expected)(actual);
25
+ *
26
+ * // Error validation
27
+ * TestValidator.error("should throw on invalid input")(() => validateInput(""));
28
+ * ```;
10
29
  */
11
30
  export namespace TestValidator {
12
31
  /**
13
- * Test whether condition is satisfied.
32
+ * Validates that a given condition evaluates to true.
33
+ *
34
+ * Supports synchronous boolean values, synchronous functions returning
35
+ * boolean, and asynchronous functions returning Promise<boolean>. The return
36
+ * type is automatically inferred based on the input type.
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * // Synchronous boolean
41
+ * TestValidator.predicate("user should exist")(user !== null);
14
42
  *
15
- * @param title Title of error message when condition is not satisfied
16
- * @return Currying function
43
+ * // Synchronous function
44
+ * TestValidator.predicate("array should be empty")(() => arr.length === 0);
45
+ *
46
+ * // Asynchronous function
47
+ * await TestValidator.predicate("database should be connected")(
48
+ * async () => await db.ping()
49
+ * );
50
+ * ```;
51
+ *
52
+ * @param title - Descriptive title used in error messages when validation
53
+ * fails
54
+ * @returns A currying function that accepts the condition to validate
55
+ * @throws Error with descriptive message when condition is not satisfied
17
56
  */
18
57
  export const predicate =
19
58
  (title: string) =>
@@ -48,16 +87,33 @@ export namespace TestValidator {
48
87
  };
49
88
 
50
89
  /**
51
- * Test whether two values are equal.
90
+ * Validates deep equality between two values using JSON comparison.
91
+ *
92
+ * Performs recursive comparison of objects and arrays. Supports an optional
93
+ * exception filter to ignore specific keys during comparison. Useful for
94
+ * validating API responses, data transformations, and object state changes.
95
+ *
96
+ * @example
97
+ * ```typescript
98
+ * // Basic equality
99
+ * TestValidator.equals("response should match expected")(expectedUser)(actualUser);
52
100
  *
53
- * If you want to validate `covers` relationship,
54
- * call smaller first and then larger.
101
+ * // Ignore timestamps in comparison
102
+ * TestValidator.equals("user data should match", (key) => key === "updatedAt")(
103
+ * expectedUser
104
+ * )(actualUser);
55
105
  *
56
- * Otherwise you wanna non equals validator, combine with {@link error}.
106
+ * // Validate API response structure
107
+ * const validateResponse = TestValidator.equals("API response structure");
108
+ * validateResponse({ id: 1, name: "John" })({ id: 1, name: "John" });
109
+ * ```;
57
110
  *
58
- * @param title Title of error message when different
59
- * @param exception Exception filter for ignoring some keys
60
- * @returns Currying function
111
+ * @param title - Descriptive title used in error messages when values differ
112
+ * @param exception - Optional filter function to exclude specific keys from
113
+ * comparison
114
+ * @returns A currying function chain: first accepts expected value, then
115
+ * actual value
116
+ * @throws Error with detailed diff information when values are not equal
61
117
  */
62
118
  export const equals =
63
119
  (title: string, exception: (key: string) => boolean = () => false) =>
@@ -75,13 +131,34 @@ export namespace TestValidator {
75
131
  };
76
132
 
77
133
  /**
78
- * Test whether error occurs.
134
+ * Validates that a function throws an error or rejects when executed.
79
135
  *
80
- * If error occurs, nothing would be happened.
136
+ * Expects the provided function to fail. If the function executes
137
+ * successfully without throwing an error or rejecting, this validator will
138
+ * throw an exception. Supports both synchronous and asynchronous functions.
81
139
  *
82
- * However, no error exists, then exception would be thrown.
140
+ * @example
141
+ * ```typescript
142
+ * // Synchronous error validation
143
+ * TestValidator.error("should reject invalid email")(
144
+ * () => validateEmail("invalid-email")
145
+ * );
83
146
  *
84
- * @param title Title of exception because of no error exists
147
+ * // Asynchronous error validation
148
+ * await TestValidator.error("should reject unauthorized access")(
149
+ * async () => await api.functional.getSecretData()
150
+ * );
151
+ *
152
+ * // Validate input validation
153
+ * TestValidator.error("should throw on empty string")(
154
+ * () => processRequiredInput("")
155
+ * );
156
+ * ```;
157
+ *
158
+ * @param title - Descriptive title used in error messages when no error
159
+ * occurs
160
+ * @returns A currying function that accepts the task function to validate
161
+ * @throws Error when the task function does not throw an error or reject
85
162
  */
86
163
  export const error =
87
164
  (title: string) =>
@@ -99,6 +176,37 @@ export namespace TestValidator {
99
176
  }
100
177
  };
101
178
 
179
+ /**
180
+ * Validates that a function throws an HTTP error with specific status codes.
181
+ *
182
+ * Specialized error validator for HTTP operations. Validates that the
183
+ * function throws an HttpError with one of the specified status codes. Useful
184
+ * for testing API endpoints, authentication, and authorization logic.
185
+ *
186
+ * @example
187
+ * ```typescript
188
+ * // Validate 401 Unauthorized
189
+ * await TestValidator.httpError("should return 401 for invalid token")(401)(
190
+ * async () => await api.functional.getProtectedResource("invalid-token")
191
+ * );
192
+ *
193
+ * // Validate multiple possible error codes
194
+ * await TestValidator.httpError("should return client error")(400, 404, 422)(
195
+ * async () => await api.functional.updateNonexistentResource(data)
196
+ * );
197
+ *
198
+ * // Validate server errors
199
+ * TestValidator.httpError("should handle server errors")(500, 502, 503)(
200
+ * () => callFaultyEndpoint()
201
+ * );
202
+ * ```;
203
+ *
204
+ * @param title - Descriptive title used in error messages
205
+ * @returns A currying function that accepts status codes, then the task
206
+ * function
207
+ * @throws Error when function doesn't throw HttpError or status code doesn't
208
+ * match
209
+ */
102
210
  export const httpError =
103
211
  (title: string) =>
104
212
  (...statuses: number[]) =>
@@ -143,6 +251,37 @@ export namespace TestValidator {
143
251
  }
144
252
  };
145
253
 
254
+ /**
255
+ * Safely executes a function and captures any errors without throwing.
256
+ *
257
+ * Utility function for error handling in tests. Executes the provided
258
+ * function and returns any error that occurs, or null if successful. Supports
259
+ * both synchronous and asynchronous functions. Useful for testing error
260
+ * conditions without stopping test execution.
261
+ *
262
+ * @example
263
+ * ```typescript
264
+ * // Synchronous error capture
265
+ * const error = TestValidator.proceed(() => {
266
+ * throw new Error("Something went wrong");
267
+ * });
268
+ * console.log(error?.message); // "Something went wrong"
269
+ *
270
+ * // Asynchronous error capture
271
+ * const asyncError = await TestValidator.proceed(async () => {
272
+ * await failingAsyncOperation();
273
+ * });
274
+ *
275
+ * // Success case
276
+ * const noError = TestValidator.proceed(() => {
277
+ * return "success";
278
+ * });
279
+ * console.log(noError); // null
280
+ * ```;
281
+ *
282
+ * @param task - Function to execute safely
283
+ * @returns Error object if function throws/rejects, null if successful
284
+ */
146
285
  export function proceed(task: () => Promise<any>): Promise<Error | null>;
147
286
  export function proceed(task: () => any): Error | null;
148
287
  export function proceed(
@@ -163,16 +302,36 @@ export namespace TestValidator {
163
302
  }
164
303
 
165
304
  /**
166
- * Validate index API.
305
+ * Validates pagination index API results against expected entity order.
167
306
  *
168
- * Test whether two indexed values are equal.
307
+ * Compares the order of entities returned by a pagination API with manually
308
+ * sorted expected results. Validates that entity IDs appear in the correct
309
+ * sequence. Commonly used for testing database queries, search results, and
310
+ * any paginated data APIs.
169
311
  *
170
- * If two values are different, then exception would be thrown.
312
+ * @example
313
+ * ```typescript
314
+ * // Test article pagination
315
+ * const expectedArticles = await db.articles.findAll({ order: 'created_at DESC' });
316
+ * const actualArticles = await api.functional.getArticles({ page: 1, limit: 10 });
171
317
  *
172
- * @param title Title of error message when different
173
- * @return Currying function
318
+ * TestValidator.index("article pagination order")(expectedArticles)(
319
+ * actualArticles,
320
+ * true // enable trace logging
321
+ * );
174
322
  *
175
- * @example https://github.com/samchon/nestia-template/blob/master/src/test/features/api/bbs/test_api_bbs_article_index_search.ts
323
+ * // Test user search results
324
+ * const manuallyFilteredUsers = allUsers.filter(u => u.name.includes("John"));
325
+ * const apiSearchResults = await api.functional.searchUsers({ query: "John" });
326
+ *
327
+ * TestValidator.index("user search results")(manuallyFilteredUsers)(
328
+ * apiSearchResults
329
+ * );
330
+ * ```;
331
+ *
332
+ * @param title - Descriptive title used in error messages when order differs
333
+ * @returns A currying function chain: expected entities, then actual entities
334
+ * @throws Error when entity order differs between expected and actual results
176
335
  */
177
336
  export const index =
178
337
  (title: string) =>
@@ -203,31 +362,53 @@ export namespace TestValidator {
203
362
  };
204
363
 
205
364
  /**
206
- * Valiate search options.
365
+ * Validates search functionality by testing API results against manual
366
+ * filtering.
367
+ *
368
+ * Comprehensive search validation that samples entities from a complete
369
+ * dataset, extracts search values, applies manual filtering, calls the search
370
+ * API, and compares results. Validates that search APIs return the correct
371
+ * subset of data matching the search criteria.
372
+ *
373
+ * @example
374
+ * ```typescript
375
+ * // Test article search functionality
376
+ * const allArticles = await db.articles.findAll();
377
+ * const searchValidator = TestValidator.search("article search API")(
378
+ * (req) => api.searchArticles(req)
379
+ * )(allArticles, 5); // test with 5 random samples
207
380
  *
208
- * Test a pagination API supporting search options.
381
+ * await searchValidator({
382
+ * fields: ["title", "content"],
383
+ * values: (article) => [article.title.split(" ")[0]], // first word
384
+ * filter: (article, [keyword]) =>
385
+ * article.title.includes(keyword) || article.content.includes(keyword),
386
+ * request: ([keyword]) => ({ q: keyword })
387
+ * });
209
388
  *
210
- * @param title Title of error message when searching is invalid
211
- * @returns Currying function
389
+ * // Test user search with multiple criteria
390
+ * await TestValidator.search("user search with filters")(
391
+ * (req) => api.getUsers(req)
392
+ * )(allUsers, 3)({
393
+ * fields: ["status", "role"],
394
+ * values: (user) => [user.status, user.role],
395
+ * filter: (user, [status, role]) =>
396
+ * user.status === status && user.role === role,
397
+ * request: ([status, role]) => ({ status, role })
398
+ * });
399
+ * ```;
212
400
  *
213
- * @example https://github.com/samchon/nestia-template/blob/master/src/test/features/api/bbs/test_api_bbs_article_index_search.ts
401
+ * @param title - Descriptive title used in error messages when search fails
402
+ * @returns A currying function chain: API getter function, then dataset and
403
+ * sample count
404
+ * @throws Error when API search results don't match manual filtering results
214
405
  */
215
406
  export const search =
216
407
  (title: string) =>
217
- /**
218
- * @param getter A pagination API function to be called
219
- */
220
408
  <Entity extends IEntity<any>, Request>(
221
409
  getter: (input: Request) => Promise<Entity[]>,
222
410
  ) =>
223
- /**
224
- * @param total Total entity records for comparison
225
- * @param sampleCount Sampling count. Default is 1
226
- */
227
411
  (total: Entity[], sampleCount: number = 1) =>
228
- /**
229
- * @param props Search properties
230
- */
231
412
  async <Values extends any[]>(
232
413
  props: ISearchProps<Entity, Values, Request>,
233
414
  ): Promise<void> => {
@@ -245,34 +426,94 @@ export namespace TestValidator {
245
426
  }
246
427
  };
247
428
 
429
+ /**
430
+ * Configuration interface for search validation functionality.
431
+ *
432
+ * Defines the structure needed to validate search operations by specifying
433
+ * how to extract search values from entities, filter the dataset manually,
434
+ * and construct API requests.
435
+ *
436
+ * @template Entity - Type of entities being searched, must have an ID field
437
+ * @template Values - Tuple type representing the search values extracted from
438
+ * entities
439
+ * @template Request - Type of the API request object
440
+ */
248
441
  export interface ISearchProps<
249
442
  Entity extends IEntity<any>,
250
443
  Values extends any[],
251
444
  Request,
252
445
  > {
446
+ /** Field names being searched, used in error messages for identification */
253
447
  fields: string[];
448
+
449
+ /**
450
+ * Extracts search values from a sample entity
451
+ *
452
+ * @param entity - The entity to extract search values from
453
+ * @returns Tuple of values used for searching
454
+ */
254
455
  values(entity: Entity): Values;
456
+
457
+ /**
458
+ * Manual filter function to determine if an entity matches search criteria
459
+ *
460
+ * @param entity - Entity to test against criteria
461
+ * @param values - Search values to match against
462
+ * @returns True if entity matches the search criteria
463
+ */
255
464
  filter(entity: Entity, values: Values): boolean;
465
+
466
+ /**
467
+ * Constructs API request object from search values
468
+ *
469
+ * @param values - Search values to include in request
470
+ * @returns Request object for the search API
471
+ */
256
472
  request(values: Values): Request;
257
473
  }
258
474
 
259
475
  /**
260
- * Validate sorting options.
476
+ * Validates sorting functionality of pagination APIs.
477
+ *
478
+ * Tests sorting operations by calling the API with sort parameters and
479
+ * validating that results are correctly ordered. Supports multiple fields,
480
+ * ascending/descending order, and optional filtering. Provides detailed error
481
+ * reporting for sorting failures.
261
482
  *
262
- * Test a pagination API supporting sorting options.
483
+ * @example
484
+ * ```typescript
485
+ * // Test single field sorting
486
+ * const sortValidator = TestValidator.sort("article sorting")(
487
+ * (sortable) => api.getArticles({ sort: sortable })
488
+ * )("created_at")(
489
+ * (a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
490
+ * );
263
491
  *
264
- * You can validate detailed sorting options both ascending and descending orders
265
- * with multiple fields. However, as it forms a complicate currying function,
266
- * I recommend you to see below example code before using.
492
+ * await sortValidator("+"); // ascending
493
+ * await sortValidator("-"); // descending
267
494
  *
268
- * @param title Title of error message when sorting is invalid
269
- * @example https://github.com/samchon/nestia-template/blob/master/src/test/features/api/bbs/test_api_bbs_article_index_sort.ts
495
+ * // Test multi-field sorting with filtering
496
+ * const userSortValidator = TestValidator.sort("user sorting")(
497
+ * (sortable) => api.getUsers({ sort: sortable })
498
+ * )("status", "created_at")(
499
+ * (a, b) => {
500
+ * if (a.status !== b.status) return a.status.localeCompare(b.status);
501
+ * return new Date(a.created_at).getTime() - new Date(b.created_at).getTime();
502
+ * },
503
+ * (user) => user.isActive // only test active users
504
+ * );
505
+ *
506
+ * await userSortValidator("+", true); // ascending with trace logging
507
+ * ```;
508
+ *
509
+ * @param title - Descriptive title used in error messages when sorting fails
510
+ * @returns A currying function chain: API getter, field names, comparator,
511
+ * then direction
512
+ * @throws Error when API results are not properly sorted according to
513
+ * specification
270
514
  */
271
515
  export const sort =
272
516
  (title: string) =>
273
- /**
274
- * @param getter A pagination API function to be called
275
- */
276
517
  <
277
518
  T extends object,
278
519
  Fields extends string,
@@ -282,18 +523,8 @@ export namespace TestValidator {
282
523
  >(
283
524
  getter: (sortable: Sortable) => Promise<T[]>,
284
525
  ) =>
285
- /**
286
- * @param fields List of fields to be sorted
287
- */
288
526
  (...fields: Fields[]) =>
289
- /**
290
- * @param comp Comparator function for validation
291
- * @param filter Filter function for data if required
292
- */
293
527
  (comp: (x: T, y: T) => number, filter?: (elem: T) => boolean) =>
294
- /**
295
- * @param direction "+" means ascending order, and "-" means descending order
296
- */
297
528
  async (direction: "+" | "-", trace: boolean = false) => {
298
529
  let data: T[] = await getter(
299
530
  fields.map((field) => `${direction}${field}` as const) as Sortable,
@@ -318,6 +549,22 @@ export namespace TestValidator {
318
549
  }
319
550
  };
320
551
 
552
+ /**
553
+ * Type alias for sortable field specifications.
554
+ *
555
+ * Represents an array of sort field specifications where each field can be
556
+ * prefixed with '+' for ascending order or '-' for descending order.
557
+ *
558
+ * @example
559
+ * ```typescript
560
+ * type UserSortable = TestValidator.Sortable<"name" | "email" | "created_at">;
561
+ * // Results in: Array<"-name" | "+name" | "-email" | "+email" | "-created_at" | "+created_at">
562
+ *
563
+ * const userSort: UserSortable = ["+name", "-created_at"];
564
+ * ```;
565
+ *
566
+ * @template Literal - String literal type representing available field names
567
+ */
321
568
  export type Sortable<Literal extends string> = Array<
322
569
  `-${Literal}` | `+${Literal}`
323
570
  >;