@nestia/e2e 7.0.0-dev.20250608 → 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.
@@ -1,87 +1,354 @@
1
1
  /**
2
- * Test validator.
2
+ * A comprehensive collection of E2E validation utilities for testing
3
+ * applications.
3
4
  *
4
- * `TestValidator` is a collection gathering E2E validation functions.
5
+ * TestValidator provides type-safe validation functions for common testing
6
+ * scenarios including condition checking, equality validation, error testing,
7
+ * HTTP error validation, pagination testing, search functionality validation,
8
+ * and sorting validation.
9
+ *
10
+ * All functions follow a currying pattern to enable reusable test
11
+ * configurations and provide detailed error messages for debugging failed
12
+ * assertions.
5
13
  *
6
14
  * @author Jeongho Nam - https://github.com/samchon
15
+ * @example
16
+ * ```typescript
17
+ * // Basic condition testing
18
+ * TestValidator.predicate("user should be authenticated")(user.isAuthenticated);
19
+ *
20
+ * // Equality validation
21
+ * TestValidator.equals("API response should match expected")(expected)(actual);
22
+ *
23
+ * // Error validation
24
+ * TestValidator.error("should throw on invalid input")(() => validateInput(""));
25
+ * ```;
7
26
  */
8
27
  export declare namespace TestValidator {
9
28
  /**
10
- * Test whether condition is satisfied.
29
+ * Validates that a given condition evaluates to true.
30
+ *
31
+ * Supports synchronous boolean values, synchronous functions returning
32
+ * boolean, and asynchronous functions returning Promise<boolean>. The return
33
+ * type is automatically inferred based on the input type.
34
+ *
35
+ * @example
36
+ * ```typescript
37
+ * // Synchronous boolean
38
+ * TestValidator.predicate("user should exist")(user !== null);
39
+ *
40
+ * // Synchronous function
41
+ * TestValidator.predicate("array should be empty")(() => arr.length === 0);
11
42
  *
12
- * @param title Title of error message when condition is not satisfied
13
- * @return Currying function
43
+ * // Asynchronous function
44
+ * await TestValidator.predicate("database should be connected")(
45
+ * async () => await db.ping()
46
+ * );
47
+ * ```;
48
+ *
49
+ * @param title - Descriptive title used in error messages when validation
50
+ * fails
51
+ * @returns A currying function that accepts the condition to validate
52
+ * @throws Error with descriptive message when condition is not satisfied
14
53
  */
15
54
  const predicate: (title: string) => <T extends boolean | (() => boolean) | (() => Promise<boolean>)>(condition: T) => T extends () => Promise<boolean> ? Promise<void> : void;
16
55
  /**
17
- * Test whether two values are equal.
56
+ * Validates deep equality between two values using JSON comparison.
57
+ *
58
+ * Performs recursive comparison of objects and arrays. Supports an optional
59
+ * exception filter to ignore specific keys during comparison. Useful for
60
+ * validating API responses, data transformations, and object state changes.
61
+ *
62
+ * @example
63
+ * ```typescript
64
+ * // Basic equality
65
+ * TestValidator.equals("response should match expected")(expectedUser)(actualUser);
18
66
  *
19
- * If you want to validate `covers` relationship,
20
- * call smaller first and then larger.
67
+ * // Ignore timestamps in comparison
68
+ * TestValidator.equals("user data should match", (key) => key === "updatedAt")(
69
+ * expectedUser
70
+ * )(actualUser);
21
71
  *
22
- * Otherwise you wanna non equals validator, combine with {@link error}.
72
+ * // Validate API response structure
73
+ * const validateResponse = TestValidator.equals("API response structure");
74
+ * validateResponse({ id: 1, name: "John" })({ id: 1, name: "John" });
75
+ * ```;
23
76
  *
24
- * @param title Title of error message when different
25
- * @param exception Exception filter for ignoring some keys
26
- * @returns Currying function
77
+ * @param title - Descriptive title used in error messages when values differ
78
+ * @param exception - Optional filter function to exclude specific keys from
79
+ * comparison
80
+ * @returns A currying function chain: first accepts expected value, then
81
+ * actual value
82
+ * @throws Error with detailed diff information when values are not equal
27
83
  */
28
84
  const equals: (title: string, exception?: (key: string) => boolean) => <T>(x: T) => (y: T) => void;
29
85
  /**
30
- * Test whether error occurs.
86
+ * Validates that a function throws an error or rejects when executed.
87
+ *
88
+ * Expects the provided function to fail. If the function executes
89
+ * successfully without throwing an error or rejecting, this validator will
90
+ * throw an exception. Supports both synchronous and asynchronous functions.
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * // Synchronous error validation
95
+ * TestValidator.error("should reject invalid email")(
96
+ * () => validateEmail("invalid-email")
97
+ * );
31
98
  *
32
- * If error occurs, nothing would be happened.
99
+ * // Asynchronous error validation
100
+ * await TestValidator.error("should reject unauthorized access")(
101
+ * async () => await api.functional.getSecretData()
102
+ * );
33
103
  *
34
- * However, no error exists, then exception would be thrown.
104
+ * // Validate input validation
105
+ * TestValidator.error("should throw on empty string")(
106
+ * () => processRequiredInput("")
107
+ * );
108
+ * ```;
35
109
  *
36
- * @param title Title of exception because of no error exists
110
+ * @param title - Descriptive title used in error messages when no error
111
+ * occurs
112
+ * @returns A currying function that accepts the task function to validate
113
+ * @throws Error when the task function does not throw an error or reject
37
114
  */
38
115
  const error: (title: string) => <T>(task: () => T) => T extends Promise<any> ? Promise<void> : void;
116
+ /**
117
+ * Validates that a function throws an HTTP error with specific status codes.
118
+ *
119
+ * Specialized error validator for HTTP operations. Validates that the
120
+ * function throws an HttpError with one of the specified status codes. Useful
121
+ * for testing API endpoints, authentication, and authorization logic.
122
+ *
123
+ * @example
124
+ * ```typescript
125
+ * // Validate 401 Unauthorized
126
+ * await TestValidator.httpError("should return 401 for invalid token")(401)(
127
+ * async () => await api.functional.getProtectedResource("invalid-token")
128
+ * );
129
+ *
130
+ * // Validate multiple possible error codes
131
+ * await TestValidator.httpError("should return client error")(400, 404, 422)(
132
+ * async () => await api.functional.updateNonexistentResource(data)
133
+ * );
134
+ *
135
+ * // Validate server errors
136
+ * TestValidator.httpError("should handle server errors")(500, 502, 503)(
137
+ * () => callFaultyEndpoint()
138
+ * );
139
+ * ```;
140
+ *
141
+ * @param title - Descriptive title used in error messages
142
+ * @returns A currying function that accepts status codes, then the task
143
+ * function
144
+ * @throws Error when function doesn't throw HttpError or status code doesn't
145
+ * match
146
+ */
39
147
  const httpError: (title: string) => (...statuses: number[]) => <T>(task: () => T) => T extends Promise<any> ? Promise<void> : void;
148
+ /**
149
+ * Safely executes a function and captures any errors without throwing.
150
+ *
151
+ * Utility function for error handling in tests. Executes the provided
152
+ * function and returns any error that occurs, or null if successful. Supports
153
+ * both synchronous and asynchronous functions. Useful for testing error
154
+ * conditions without stopping test execution.
155
+ *
156
+ * @example
157
+ * ```typescript
158
+ * // Synchronous error capture
159
+ * const error = TestValidator.proceed(() => {
160
+ * throw new Error("Something went wrong");
161
+ * });
162
+ * console.log(error?.message); // "Something went wrong"
163
+ *
164
+ * // Asynchronous error capture
165
+ * const asyncError = await TestValidator.proceed(async () => {
166
+ * await failingAsyncOperation();
167
+ * });
168
+ *
169
+ * // Success case
170
+ * const noError = TestValidator.proceed(() => {
171
+ * return "success";
172
+ * });
173
+ * console.log(noError); // null
174
+ * ```;
175
+ *
176
+ * @param task - Function to execute safely
177
+ * @returns Error object if function throws/rejects, null if successful
178
+ */
40
179
  function proceed(task: () => Promise<any>): Promise<Error | null>;
41
180
  function proceed(task: () => any): Error | null;
42
181
  /**
43
- * Validate index API.
182
+ * Validates pagination index API results against expected entity order.
183
+ *
184
+ * Compares the order of entities returned by a pagination API with manually
185
+ * sorted expected results. Validates that entity IDs appear in the correct
186
+ * sequence. Commonly used for testing database queries, search results, and
187
+ * any paginated data APIs.
188
+ *
189
+ * @example
190
+ * ```typescript
191
+ * // Test article pagination
192
+ * const expectedArticles = await db.articles.findAll({ order: 'created_at DESC' });
193
+ * const actualArticles = await api.functional.getArticles({ page: 1, limit: 10 });
44
194
  *
45
- * Test whether two indexed values are equal.
195
+ * TestValidator.index("article pagination order")(expectedArticles)(
196
+ * actualArticles,
197
+ * true // enable trace logging
198
+ * );
46
199
  *
47
- * If two values are different, then exception would be thrown.
200
+ * // Test user search results
201
+ * const manuallyFilteredUsers = allUsers.filter(u => u.name.includes("John"));
202
+ * const apiSearchResults = await api.functional.searchUsers({ query: "John" });
48
203
  *
49
- * @param title Title of error message when different
50
- * @return Currying function
204
+ * TestValidator.index("user search results")(manuallyFilteredUsers)(
205
+ * apiSearchResults
206
+ * );
207
+ * ```;
51
208
  *
52
- * @example https://github.com/samchon/nestia-template/blob/master/src/test/features/api/bbs/test_api_bbs_article_index_search.ts
209
+ * @param title - Descriptive title used in error messages when order differs
210
+ * @returns A currying function chain: expected entities, then actual entities
211
+ * @throws Error when entity order differs between expected and actual results
53
212
  */
54
213
  const index: (title: string) => <Solution extends IEntity<any>>(expected: Solution[]) => <Summary extends IEntity<any>>(gotten: Summary[], trace?: boolean) => void;
55
214
  /**
56
- * Valiate search options.
215
+ * Validates search functionality by testing API results against manual
216
+ * filtering.
57
217
  *
58
- * Test a pagination API supporting search options.
218
+ * Comprehensive search validation that samples entities from a complete
219
+ * dataset, extracts search values, applies manual filtering, calls the search
220
+ * API, and compares results. Validates that search APIs return the correct
221
+ * subset of data matching the search criteria.
59
222
  *
60
- * @param title Title of error message when searching is invalid
61
- * @returns Currying function
223
+ * @example
224
+ * ```typescript
225
+ * // Test article search functionality
226
+ * const allArticles = await db.articles.findAll();
227
+ * const searchValidator = TestValidator.search("article search API")(
228
+ * (req) => api.searchArticles(req)
229
+ * )(allArticles, 5); // test with 5 random samples
62
230
  *
63
- * @example https://github.com/samchon/nestia-template/blob/master/src/test/features/api/bbs/test_api_bbs_article_index_search.ts
231
+ * await searchValidator({
232
+ * fields: ["title", "content"],
233
+ * values: (article) => [article.title.split(" ")[0]], // first word
234
+ * filter: (article, [keyword]) =>
235
+ * article.title.includes(keyword) || article.content.includes(keyword),
236
+ * request: ([keyword]) => ({ q: keyword })
237
+ * });
238
+ *
239
+ * // Test user search with multiple criteria
240
+ * await TestValidator.search("user search with filters")(
241
+ * (req) => api.getUsers(req)
242
+ * )(allUsers, 3)({
243
+ * fields: ["status", "role"],
244
+ * values: (user) => [user.status, user.role],
245
+ * filter: (user, [status, role]) =>
246
+ * user.status === status && user.role === role,
247
+ * request: ([status, role]) => ({ status, role })
248
+ * });
249
+ * ```;
250
+ *
251
+ * @param title - Descriptive title used in error messages when search fails
252
+ * @returns A currying function chain: API getter function, then dataset and
253
+ * sample count
254
+ * @throws Error when API search results don't match manual filtering results
64
255
  */
65
256
  const search: (title: string) => <Entity extends IEntity<any>, Request>(getter: (input: Request) => Promise<Entity[]>) => (total: Entity[], sampleCount?: number) => <Values extends any[]>(props: ISearchProps<Entity, Values, Request>) => Promise<void>;
257
+ /**
258
+ * Configuration interface for search validation functionality.
259
+ *
260
+ * Defines the structure needed to validate search operations by specifying
261
+ * how to extract search values from entities, filter the dataset manually,
262
+ * and construct API requests.
263
+ *
264
+ * @template Entity - Type of entities being searched, must have an ID field
265
+ * @template Values - Tuple type representing the search values extracted from
266
+ * entities
267
+ * @template Request - Type of the API request object
268
+ */
66
269
  interface ISearchProps<Entity extends IEntity<any>, Values extends any[], Request> {
270
+ /** Field names being searched, used in error messages for identification */
67
271
  fields: string[];
272
+ /**
273
+ * Extracts search values from a sample entity
274
+ *
275
+ * @param entity - The entity to extract search values from
276
+ * @returns Tuple of values used for searching
277
+ */
68
278
  values(entity: Entity): Values;
279
+ /**
280
+ * Manual filter function to determine if an entity matches search criteria
281
+ *
282
+ * @param entity - Entity to test against criteria
283
+ * @param values - Search values to match against
284
+ * @returns True if entity matches the search criteria
285
+ */
69
286
  filter(entity: Entity, values: Values): boolean;
287
+ /**
288
+ * Constructs API request object from search values
289
+ *
290
+ * @param values - Search values to include in request
291
+ * @returns Request object for the search API
292
+ */
70
293
  request(values: Values): Request;
71
294
  }
72
295
  /**
73
- * Validate sorting options.
296
+ * Validates sorting functionality of pagination APIs.
297
+ *
298
+ * Tests sorting operations by calling the API with sort parameters and
299
+ * validating that results are correctly ordered. Supports multiple fields,
300
+ * ascending/descending order, and optional filtering. Provides detailed error
301
+ * reporting for sorting failures.
302
+ *
303
+ * @example
304
+ * ```typescript
305
+ * // Test single field sorting
306
+ * const sortValidator = TestValidator.sort("article sorting")(
307
+ * (sortable) => api.getArticles({ sort: sortable })
308
+ * )("created_at")(
309
+ * (a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
310
+ * );
74
311
  *
75
- * Test a pagination API supporting sorting options.
312
+ * await sortValidator("+"); // ascending
313
+ * await sortValidator("-"); // descending
76
314
  *
77
- * You can validate detailed sorting options both ascending and descending orders
78
- * with multiple fields. However, as it forms a complicate currying function,
79
- * I recommend you to see below example code before using.
315
+ * // Test multi-field sorting with filtering
316
+ * const userSortValidator = TestValidator.sort("user sorting")(
317
+ * (sortable) => api.getUsers({ sort: sortable })
318
+ * )("status", "created_at")(
319
+ * (a, b) => {
320
+ * if (a.status !== b.status) return a.status.localeCompare(b.status);
321
+ * return new Date(a.created_at).getTime() - new Date(b.created_at).getTime();
322
+ * },
323
+ * (user) => user.isActive // only test active users
324
+ * );
80
325
  *
81
- * @param title Title of error message when sorting is invalid
82
- * @example https://github.com/samchon/nestia-template/blob/master/src/test/features/api/bbs/test_api_bbs_article_index_sort.ts
326
+ * await userSortValidator("+", true); // ascending with trace logging
327
+ * ```;
328
+ *
329
+ * @param title - Descriptive title used in error messages when sorting fails
330
+ * @returns A currying function chain: API getter, field names, comparator,
331
+ * then direction
332
+ * @throws Error when API results are not properly sorted according to
333
+ * specification
83
334
  */
84
335
  const sort: (title: string) => <T extends object, Fields extends string, Sortable extends Array<`-${Fields}` | `+${Fields}`> = Array<`-${Fields}` | `+${Fields}`>>(getter: (sortable: Sortable) => Promise<T[]>) => (...fields: Fields[]) => (comp: (x: T, y: T) => number, filter?: (elem: T) => boolean) => (direction: "+" | "-", trace?: boolean) => Promise<void>;
336
+ /**
337
+ * Type alias for sortable field specifications.
338
+ *
339
+ * Represents an array of sort field specifications where each field can be
340
+ * prefixed with '+' for ascending order or '-' for descending order.
341
+ *
342
+ * @example
343
+ * ```typescript
344
+ * type UserSortable = TestValidator.Sortable<"name" | "email" | "created_at">;
345
+ * // Results in: Array<"-name" | "+name" | "-email" | "+email" | "-created_at" | "+created_at">
346
+ *
347
+ * const userSort: UserSortable = ["+name", "-created_at"];
348
+ * ```;
349
+ *
350
+ * @template Literal - String literal type representing available field names
351
+ */
85
352
  type Sortable<Literal extends string> = Array<`-${Literal}` | `+${Literal}`>;
86
353
  }
87
354
  interface IEntity<Type extends string | number | bigint> {