@omnitron-dev/testing 0.4.6 → 0.4.9

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.
Files changed (3) hide show
  1. package/README.md +14 -21
  2. package/package.json +12 -12
  3. package/src/async/README.md +18 -328
package/README.md CHANGED
@@ -1,27 +1,19 @@
1
1
  # @omnitron-dev/testing
2
2
 
3
- > Cross-runtime testing utilities for the Omni ecosystem
3
+ Shared test utilities for Omni packages, including runtime adapters, asynchronous assertions and isolated infrastructure fixtures.
4
4
 
5
- Part of the [Omni](../../README.md) monorepo — Fullstack Type-Safe RPC Framework.
5
+ ## Capabilities
6
6
 
7
- ## Installation
7
+ - Explicit Vitest, Bun, Deno and Node test entry points.
8
+ - Titan application helpers, performance tools and test environment configuration.
9
+ - Docker and Redis fixtures for integration tests.
8
10
 
9
- ```bash
11
+ ## Quick start
12
+
13
+ ```sh
10
14
  pnpm add -D @omnitron-dev/testing
11
15
  ```
12
16
 
13
- ## Overview
14
-
15
- Shared testing helpers, fixtures, and utilities used across Omni packages. Provides runtime-agnostic test infrastructure that works with both Vitest and Jest.
16
-
17
- ## Redis fixtures
18
-
19
- `createRedisTestFixture` from `@omnitron-dev/testing/titan` uses the same
20
- `resolveTestRedisEndpoint()` as the integration suites. It reads the endpoint
21
- published by global setup, then the test environment. Without setup, configure
22
- `TEST_REDIS_HOST` and `TEST_REDIS_PORT`; the default test port is **16379**, never
23
- the developer's Redis on 6379.
24
-
25
17
  ```ts
26
18
  import { createRedisTestFixture } from '@omnitron-dev/testing/titan';
27
19
 
@@ -33,11 +25,12 @@ try {
33
25
  }
34
26
  ```
35
27
 
36
- Cleanup flushes the selected scratch database and closes the clients even when
37
- flushing fails. Use a dedicated test Redis. Initialization failure also closes
38
- allocated connections. Mock mode requires a mock fixture or an explicit real
39
- endpoint; it does not silently connect to a developer service.
28
+ Use a dedicated test Redis: cleanup flushes the selected database. The fixture reads the endpoint published by global setup, then `TEST_REDIS_HOST` and `TEST_REDIS_PORT`; its default test port is `16379`. Mock mode requires a mock fixture or an explicit real endpoint and does not connect to a developer service silently.
29
+
30
+ ## Documentation
31
+
32
+ [Public API](src/index.ts) · [Package exports](package.json) · [Omni](../../README.md)
40
33
 
41
34
  ## License
42
35
 
43
- MIT
36
+ [MIT](../../LICENSE).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omnitron-dev/testing",
3
- "version": "0.4.6",
3
+ "version": "0.4.9",
4
4
  "description": "Cross-runtime testing utilities",
5
5
  "author": "LuxQuant",
6
6
  "license": "MIT",
@@ -72,11 +72,11 @@
72
72
  "zod": "^4.6.7"
73
73
  },
74
74
  "devDependencies": {
75
- "@omnitron-dev/eventemitter": "0.4.6",
76
- "@omnitron-dev/titan": "0.4.6",
77
- "@omnitron-dev/titan-database": "0.4.6",
78
- "@omnitron-dev/titan-pm": "0.4.6",
79
- "@omnitron-dev/titan-redis": "0.4.6",
75
+ "@omnitron-dev/eventemitter": "0.4.9",
76
+ "@omnitron-dev/titan": "0.4.9",
77
+ "@omnitron-dev/titan-database": "0.4.9",
78
+ "@omnitron-dev/titan-pm": "0.4.9",
79
+ "@omnitron-dev/titan-redis": "0.4.9",
80
80
  "@types/bun": "^1.4.4",
81
81
  "ioredis": "^6.0.0",
82
82
  "pino": "^10.4.0",
@@ -85,11 +85,11 @@
85
85
  "@typescript/native": "npm:typescript@^7.0.2"
86
86
  },
87
87
  "peerDependencies": {
88
- "@omnitron-dev/eventemitter": "0.4.6",
89
- "@omnitron-dev/titan": "0.4.6",
90
- "@omnitron-dev/titan-database": "0.4.6",
91
- "@omnitron-dev/titan-pm": "0.4.6",
92
- "@omnitron-dev/titan-redis": "0.4.6",
88
+ "@omnitron-dev/eventemitter": "0.4.9",
89
+ "@omnitron-dev/titan": "0.4.9",
90
+ "@omnitron-dev/titan-database": "0.4.9",
91
+ "@omnitron-dev/titan-pm": "0.4.9",
92
+ "@omnitron-dev/titan-redis": "0.4.9",
93
93
  "bun": "*",
94
94
  "ioredis": "^5.11.1 || ^6.0.0",
95
95
  "pino": "^10.3.1",
@@ -145,7 +145,7 @@
145
145
  "publishConfig": {
146
146
  "access": "public"
147
147
  },
148
- "gitHead": "3a912fa181e97ddd238a28bb355cd7445c1b7364",
148
+ "gitHead": "c6005ff1d0cde480cfa6b0bc346c9b53b2e638bf",
149
149
  "scripts": {
150
150
  "build": "../../scripts/build-package.sh -p tsconfig.json",
151
151
  "build:titan": "rm -rf dist/titan && NODE_OPTIONS='--max-old-space-size=8192' tsc -p tsconfig.titan.json",
@@ -1,336 +1,26 @@
1
- # Async Testing Utilities
1
+ # Async test helpers
2
2
 
3
- Comprehensive utilities for testing asynchronous code in JavaScript/TypeScript.
3
+ Import these helpers from `@omnitron-dev/testing/async`. They coordinate asynchronous tests, observe events, and bound how long an assertion waits.
4
4
 
5
- ## Installation
5
+ ```ts
6
+ import { createDeferred, withTimeout } from '@omnitron-dev/testing/async';
6
7
 
7
- ```bash
8
- pnpm add -D @omnitron-dev/testing
8
+ const ready = createDeferred<string>();
9
+ const result = withTimeout(ready.promise, 1_000, 'Service did not become ready');
10
+ ready.resolve('ready');
11
+ await result;
9
12
  ```
10
13
 
11
- ## Usage
14
+ | Helper | Purpose |
15
+ | --- | --- |
16
+ | [`createDeferred`, `DeferredPromise`, `defer`](deferred.ts) | Explicitly resolve or reject a promise |
17
+ | [`waitFor`, `waitForCondition`, `delay`, `flushPromises`](wait.ts) | Poll a condition or advance asynchronous work |
18
+ | [`retry`, `withTimeout`](retry.ts) | Retry an operation or time out waiting for a promise |
19
+ | [Event trackers and collectors](events.ts) | Record calls and await event sequences |
20
+ | [Mock timer controller](mock-timer.ts) | Manage fake timers in a test |
12
21
 
13
- Import from the main package or the async submodule:
22
+ `withTimeout` rejects the wait; it does not cancel the underlying operation. `waitFor` checks its deadline between condition evaluations, so the condition must itself settle. Always release resources owned by the operation in teardown.
14
23
 
15
- ```typescript
16
- // Import from main package
17
- import { defer, waitFor, retry } from '@omnitron-dev/testing';
24
+ The current `retry` option named `retries` is the total attempt count, including the first attempt. Its default is three attempts. Choose explicit bounds for tests that exercise failure paths.
18
25
 
19
- // Or import from async submodule
20
- import { defer, waitFor, retry } from '@omnitron-dev/testing/async';
21
- ```
22
-
23
- ## API Reference
24
-
25
- ### Deferred Promises
26
-
27
- #### `DeferredPromise<T>`
28
- Class for creating a promise with external control over resolution/rejection.
29
-
30
- ```typescript
31
- const deferred = new DeferredPromise<string>();
32
- setTimeout(() => deferred.resolve('done'), 1000);
33
- await deferred.promise; // 'done'
34
- console.log(deferred.isSettled); // true
35
- ```
36
-
37
- #### `createDeferred<T>()`
38
- Factory function for creating deferred promises.
39
-
40
- ```typescript
41
- const deferred = createDeferred<number>();
42
- deferred.resolve(42);
43
- ```
44
-
45
- #### `defer<T>()`
46
- Lightweight deferred promise (backward compatible).
47
-
48
- ```typescript
49
- const deferred = defer<string>();
50
- deferred.resolve('success');
51
- await deferred.promise;
52
- ```
53
-
54
- ### Retry and Timeout
55
-
56
- #### `retry<T>(fn, options?)`
57
- Retry an async operation with exponential backoff.
58
-
59
- ```typescript
60
- const result = await retry(
61
- async () => fetchData(),
62
- {
63
- retries: 5,
64
- delay: 100,
65
- backoff: 2,
66
- onRetry: (error, attempt) => console.log(`Retry ${attempt}`)
67
- }
68
- );
69
- ```
70
-
71
- **Options:**
72
- - `retries`: Maximum retry attempts (default: 3)
73
- - `delay`: Initial delay in ms (default: 100)
74
- - `backoff`: Backoff multiplier (default: 2)
75
- - `onRetry`: Callback on each retry
76
-
77
- #### `withTimeout<T>(promise, timeout?, errorMessage?)`
78
- Race a promise against a timeout.
79
-
80
- ```typescript
81
- const result = await withTimeout(
82
- fetchData(),
83
- 5000,
84
- 'Data fetch timed out'
85
- );
86
- ```
87
-
88
- ### Wait Utilities
89
-
90
- #### `waitFor(condition, options?)`
91
- Wait for a condition to become true.
92
-
93
- ```typescript
94
- await waitFor(
95
- () => element.isVisible(),
96
- { timeout: 3000, interval: 100, message: 'Element not visible' }
97
- );
98
- ```
99
-
100
- #### `waitForCondition(condition, timeout?, interval?)`
101
- Alternative API for waiting on conditions.
102
-
103
- ```typescript
104
- await waitForCondition(
105
- () => counter > 10,
106
- 5000,
107
- 100
108
- );
109
- ```
110
-
111
- #### `delay(ms)`
112
- Simple async sleep utility.
113
-
114
- ```typescript
115
- await delay(1000); // Wait 1 second
116
- ```
117
-
118
- #### `nextTick()`
119
- Wait for the next event loop tick.
120
-
121
- ```typescript
122
- emitter.emit('event');
123
- await nextTick();
124
- // Event handlers have now executed
125
- ```
126
-
127
- #### `flushPromises()`
128
- Flush all pending promises in the event loop.
129
-
130
- ```typescript
131
- Promise.resolve().then(() => { executed = true });
132
- await flushPromises();
133
- expect(executed).toBe(true);
134
- ```
135
-
136
- ### Event Utilities
137
-
138
- #### `EventListenerTracker`
139
- Track event listeners for automatic cleanup.
140
-
141
- ```typescript
142
- const tracker = new EventListenerTracker();
143
- tracker.on(emitter, 'data', handler);
144
- tracker.once(emitter, 'error', errorHandler);
145
-
146
- // In cleanup
147
- tracker.cleanup(); // Removes all tracked listeners
148
- ```
149
-
150
- #### `EventCollector<T>`
151
- Collect events for inspection and assertions.
152
-
153
- ```typescript
154
- const collector = new EventCollector(emitter);
155
- collector.collect('data');
156
-
157
- // Trigger events...
158
-
159
- const events = collector.getEvents('data');
160
- expect(events).toHaveLength(3);
161
-
162
- collector.assertEmitted('data', 3);
163
- collector.clear();
164
- collector.stop();
165
- ```
166
-
167
- #### `waitForEvents(target, events, timeout?)`
168
- Wait for multiple events to be emitted.
169
-
170
- ```typescript
171
- const [userData, profileData] = await waitForEvents(
172
- emitter,
173
- ['user', 'profile'],
174
- 3000
175
- );
176
- ```
177
-
178
- #### `collectEvents<T>(target, event, condition, timeout?)`
179
- Collect events until a condition is met.
180
-
181
- ```typescript
182
- const events = await collectEvents(
183
- emitter,
184
- 'data',
185
- (events) => events.length >= 5,
186
- 3000
187
- );
188
- ```
189
-
190
- #### `createEventSpy(target, event)`
191
- Create a spy to record events.
192
-
193
- ```typescript
194
- const spy = createEventSpy(emitter, 'data');
195
- // Trigger events...
196
- expect(spy.events).toHaveLength(3);
197
- spy.clear();
198
- ```
199
-
200
- ### Mock Timers
201
-
202
- #### `MockTimerController`
203
- Manual control over timers for deterministic testing.
204
-
205
- ```typescript
206
- const timer = new MockTimerController();
207
- timer.install();
208
-
209
- let executed = false;
210
- setTimeout(() => { executed = true }, 1000);
211
-
212
- timer.tick(500); // executed is still false
213
- timer.tick(500); // executed is now true
214
-
215
- timer.restore();
216
- ```
217
-
218
- **Methods:**
219
- - `install()`: Replace native timers
220
- - `restore()`: Restore native timers
221
- - `tick(ms)`: Advance time by ms
222
- - `getCurrentTime()`: Get current mock time
223
- - `getPendingCount()`: Get number of pending timers
224
- - `clearAll()`: Clear all pending timers
225
- - `reset()`: Reset to initial state
226
-
227
- #### `createMockTimer()`
228
- Factory function for creating mock timers.
229
-
230
- ```typescript
231
- const timer = createMockTimer();
232
- timer.install();
233
- // ... test code ...
234
- timer.restore();
235
- ```
236
-
237
- ## Error Handling
238
-
239
- All async utilities use typed errors from `@omnitron-dev/testing/errors`:
240
-
241
- - `TimeoutError`: Thrown when operations timeout
242
- - `TestingError`: Base class for testing errors
243
-
244
- ```typescript
245
- import { TimeoutError } from '@omnitron-dev/testing';
246
-
247
- try {
248
- await waitFor(() => false, { timeout: 100 });
249
- } catch (error) {
250
- if (error instanceof TimeoutError) {
251
- console.log('Operation timed out');
252
- }
253
- }
254
- ```
255
-
256
- ## Examples
257
-
258
- ### Testing Event Sequences
259
-
260
- ```typescript
261
- import { EventCollector, delay } from '@omnitron-dev/testing/async';
262
-
263
- test('event sequence', async () => {
264
- const emitter = new EventEmitter();
265
- const collector = new EventCollector(emitter);
266
-
267
- collector.collect('start');
268
- collector.collect('data');
269
- collector.collect('end');
270
-
271
- // Trigger events
272
- await processData(emitter);
273
-
274
- collector.assertEmitted('start', 1);
275
- collector.assertEmitted('data', 5);
276
- collector.assertEmitted('end', 1);
277
-
278
- collector.stop();
279
- });
280
- ```
281
-
282
- ### Retrying Flaky Operations
283
-
284
- ```typescript
285
- import { retry } from '@omnitron-dev/testing/async';
286
-
287
- test('retry flaky operation', async () => {
288
- const result = await retry(
289
- async () => {
290
- const response = await fetch('/api/data');
291
- if (!response.ok) throw new Error('Failed');
292
- return response.json();
293
- },
294
- {
295
- retries: 3,
296
- delay: 100,
297
- backoff: 2,
298
- onRetry: (error, attempt) => {
299
- console.log(`Retry ${attempt}: ${error.message}`);
300
- }
301
- }
302
- );
303
-
304
- expect(result).toBeDefined();
305
- });
306
- ```
307
-
308
- ### Testing Time-Dependent Code
309
-
310
- ```typescript
311
- import { MockTimerController } from '@omnitron-dev/testing/async';
312
-
313
- test('debounce function', () => {
314
- const timer = new MockTimerController();
315
- timer.install();
316
-
317
- let count = 0;
318
- const debounced = debounce(() => { count++; }, 100);
319
-
320
- debounced();
321
- debounced();
322
- debounced();
323
-
324
- timer.tick(50);
325
- expect(count).toBe(0);
326
-
327
- timer.tick(50);
328
- expect(count).toBe(1);
329
-
330
- timer.restore();
331
- });
332
- ```
333
-
334
- ## License
335
-
336
- MIT
26
+ [The export list](index.ts) defines the available functions and types.