@trackunit/react-test-setup 1.0.0

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.
package/index.esm.js ADDED
@@ -0,0 +1,662 @@
1
+ import failOnConsole from 'jest-fail-on-console';
2
+ import { jsx } from 'react/jsx-runtime';
3
+ import { APILoadingStatus } from '@vis.gl/react-google-maps';
4
+ import { initialize } from '@googlemaps/jest-mocks';
5
+ import '@testing-library/jest-dom';
6
+ import { cleanup, act } from '@testing-library/react';
7
+ import { Temporal } from '@js-temporal/polyfill';
8
+ import { Globals } from '@react-spring/web';
9
+
10
+ /**
11
+ * Sets up a mock implementation for HTML Canvas API in testing environments.
12
+ *
13
+ * This function uses jest-canvas-mock to provide a mock implementation of the
14
+ * HTML Canvas API, allowing tests to run without requiring a real DOM canvas.
15
+ * Useful for testing components that use canvas rendering.
16
+ *
17
+ * @example
18
+ * // In your jest setup file
19
+ * import { setupCanvasMock } from '@trackunit/react-test-setup';
20
+ *
21
+ * setupCanvasMock();
22
+ */
23
+ const setupCanvasMock = () => {
24
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
25
+ require("jest-canvas-mock");
26
+ };
27
+
28
+ /**
29
+ * This will make your tests fail if they log to console.error during the tests.
30
+ * See more details here: https://www.npmjs.com/package/jest-fail-on-console
31
+ *
32
+ * If your tests logs to console.error on purpose, you should spy on the console like so:
33
+ * ```
34
+ * jest.spyOn(console, 'error').mockImplementation()
35
+ * // Do your logic ...
36
+ * expect(console.error).toHaveBeenCalledWith('your error message')
37
+ * ```
38
+ */
39
+ const setupFailOnConsole = (overrides = {}) => {
40
+ failOnConsole({
41
+ shouldFailOnError: true,
42
+ shouldFailOnWarn: false,
43
+ ...overrides,
44
+ });
45
+ };
46
+
47
+ const getPlacePredictionsMock = jest.fn();
48
+ /**
49
+ * Sets up mocks for Google Maps API and @vis.gl/react-google-maps components in testing environments.
50
+ *
51
+ * This function mocks both the Google Maps JavaScript API and React components from @vis.gl/react-google-maps.
52
+ * It provides mock implementations of Maps, Markers, Geocoder, geometry functions, and places services,
53
+ * allowing tests of map-dependent components to run without requiring the actual Google Maps API.
54
+ *
55
+ * Key features:
56
+ * - Mocks core Map and Marker components with simple test-friendly implementations
57
+ * - Provides placeholders for Google Maps geometry calculations
58
+ * - Stubs out Places API services
59
+ * - Makes map-related hooks always return loaded state
60
+ *
61
+ * @example
62
+ * // In your jest setup file
63
+ * import { setupGoogleMaps } from '@trackunit/react-test-setup';
64
+ *
65
+ * setupGoogleMaps();
66
+ */
67
+ const setupGoogleMaps = () => {
68
+ //To create @vis.gl/react-google-maps mock, the initialization needs to be called
69
+ initialize();
70
+ jest.mock("@vis.gl/react-google-maps", () => {
71
+ const originalModule = jest.requireActual("@vis.gl/react-google-maps");
72
+ const mapOptions = { mapId: "Map 1" };
73
+ const map = new google.maps.Map(document.createElement("div"), mapOptions);
74
+ const AdvancedMarkerMock = jest.fn(props => {
75
+ return (jsx("div", { "data-position": JSON.stringify(props.position), "data-testid": "marker", children: props.children }));
76
+ });
77
+ const MapMock = jest.fn(props => {
78
+ return jsx("div", { "data-testid": "map", children: props.children });
79
+ });
80
+ const MapMarkerMock = jest.fn(props => {
81
+ return jsx("div", { "data-testid": "map", children: props.children });
82
+ });
83
+ return {
84
+ ...originalModule,
85
+ useApiLoadingStatus: () => APILoadingStatus.LOADED,
86
+ useApiIsLoaded: () => true,
87
+ useMap: () => map,
88
+ AdvancedMarker: AdvancedMarkerMock,
89
+ Map: MapMock,
90
+ Marker: MapMarkerMock,
91
+ };
92
+ });
93
+ beforeEach(() => {
94
+ initialize();
95
+ //Adding extras
96
+ global.window.google.maps = {
97
+ ...global.window.google.maps,
98
+ Geocoder: jest.fn(),
99
+ geometry: {
100
+ ...global.window.google.maps.geometry,
101
+ spherical: {
102
+ computeDistanceBetween: jest.fn(),
103
+ computeArea: jest.fn(),
104
+ computeHeading: jest.fn(),
105
+ computeLength: jest.fn(),
106
+ computeOffset: jest.fn(),
107
+ computeOffsetOrigin: jest.fn(),
108
+ computeSignedArea: jest.fn(),
109
+ interpolate: jest.fn(),
110
+ },
111
+ },
112
+ places: {
113
+ ...global.window.google.maps.places,
114
+ AutocompleteService: jest.fn().mockImplementation(() => ({
115
+ ...global.window.google.maps.places,
116
+ getPlacePredictions: getPlacePredictionsMock,
117
+ })),
118
+ },
119
+ };
120
+ });
121
+ };
122
+
123
+ /**
124
+ * Mock helmet module
125
+ * See more details here: https://www.npmjs.com/package/react-helmet-async
126
+ */
127
+ const setupHelmetMock = () => {
128
+ jest.mock("react-helmet-async", () => ({
129
+ Helmet: () => null,
130
+ HelmetProvider: () => null,
131
+ }));
132
+ };
133
+
134
+ /* eslint-disable @typescript-eslint/explicit-member-accessibility */
135
+ /**
136
+ * Mocks the IntersectionObserver API for testing environments.
137
+ *
138
+ * This function adds a mock implementation of the IntersectionObserver API to the global window object.
139
+ * The mock implementation provides all the necessary methods (observe, unobserve, disconnect, takeRecords)
140
+ * but with empty implementations, allowing tests of components that use IntersectionObserver to run
141
+ * without errors in Jest's JSDOM environment.
142
+ *
143
+ * Useful for testing components that rely on:
144
+ * - Lazy loading
145
+ * - Infinite scrolling
146
+ * - Visibility-based rendering
147
+ * - Any other intersection-based functionality
148
+ *
149
+ * @example
150
+ * // In your jest setup file
151
+ * import { setupIntersectionObserver } from '@trackunit/react-test-setup';
152
+ *
153
+ * setupIntersectionObserver();
154
+ */
155
+ const setupIntersectionObserver = () => (window.IntersectionObserver = MockIntersectionObserver);
156
+ class MockIntersectionObserver {
157
+ constructor() {
158
+ this.root = null;
159
+ this.rootMargin = "";
160
+ this.thresholds = [];
161
+ }
162
+ disconnect() {
163
+ // Empty
164
+ }
165
+ observe() {
166
+ // Empty
167
+ }
168
+ takeRecords() {
169
+ return [];
170
+ }
171
+ unobserve() {
172
+ // Empty
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Mocks the window.matchMedia API for testing environments.
178
+ *
179
+ * This function creates a mock implementation of the window.matchMedia method that
180
+ * is commonly used for responsive design and media queries. The mock always returns
181
+ * a MediaQueryList-like object with standard methods and properties, but with default
182
+ * values (matches set to false).
183
+ *
184
+ * This allows tests of components that use media queries to run without errors in
185
+ * Jest's JSDOM environment, which doesn't implement matchMedia natively.
186
+ *
187
+ * Ideal for testing:
188
+ * - Responsive components
189
+ * - Components that adapt to screen size changes
190
+ * - Components that use CSS media query matching in JavaScript
191
+ *
192
+ * @example
193
+ * // In your jest setup file
194
+ * import { setupMatchMediaMock } from '@trackunit/react-test-setup';
195
+ *
196
+ * setupMatchMediaMock();
197
+ */
198
+ const setupMatchMediaMock = () => {
199
+ Object.defineProperty(window, "matchMedia", {
200
+ writable: true,
201
+ value: jest.fn().mockImplementation(query => ({
202
+ matches: false,
203
+ media: query,
204
+ onchange: null,
205
+ addListener: jest.fn(), // Deprecated
206
+ removeListener: jest.fn(), // Deprecated
207
+ addEventListener: jest.fn(),
208
+ removeEventListener: jest.fn(),
209
+ dispatchEvent: jest.fn(),
210
+ })),
211
+ });
212
+ };
213
+
214
+ /**
215
+ * Flushes all promises in the queue.
216
+ * This is useful when testing async code.
217
+ *
218
+ * @param waitTimeInMS - The amount of time to wait before resolving the promise.
219
+ * @returns {Promise<void>} - Returns a promise that resolves after the wait time.
220
+ */
221
+ const flushPromisesInAct = (waitTimeInMS = 0) => {
222
+ return act(() => {
223
+ return new Promise(resolve => {
224
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
225
+ if (global.ORG_setTimeout) {
226
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
227
+ return global.ORG_setTimeout(() => global.ORG_setTimeout(resolve, waitTimeInMS), 1);
228
+ }
229
+ else {
230
+ setTimeout(() => setTimeout(resolve, waitTimeInMS), 1);
231
+ }
232
+ });
233
+ });
234
+ };
235
+ afterEach(async () => {
236
+ jest.clearAllMocks();
237
+ cleanup();
238
+ await flushPromisesInAct();
239
+ });
240
+ /**
241
+ * Sets up React Testing Library and Okta authentication mocks for testing.
242
+ *
243
+ * This function configures the testing environment with essential mocks for Okta authentication,
244
+ * which is necessary for testing components that use Okta for authentication. It creates
245
+ * mock implementations of Okta authentication objects, tokens, and authentication state,
246
+ * allowing tests to run without requiring an actual Okta authentication flow.
247
+ *
248
+ * The module also imports @testing-library/jest-dom to extend Jest with DOM testing assertions
249
+ * and sets up afterEach hooks to clear mocks and clean up after each test.
250
+ *
251
+ * Key features:
252
+ * - Mocks Okta tokens and authentication state
253
+ * - Creates mock implementations of Okta auth methods
254
+ * - Extends Jest with DOM testing assertions
255
+ * - Automatically cleans up after each test
256
+ *
257
+ * @example
258
+ * // In your jest setup file
259
+ * import { setupReactTestingLibrary } from '@trackunit/react-test-setup';
260
+ *
261
+ * setupReactTestingLibrary();
262
+ */
263
+ const setupReactTestingLibrary = () => {
264
+ const mockedClaims = {
265
+ sub: "sub",
266
+ name: "user",
267
+ };
268
+ const mockedIdToken = {
269
+ idToken: "idToken",
270
+ claims: mockedClaims,
271
+ expiresAt: Date.now(),
272
+ authorizeUrl: "authorize.url",
273
+ scopes: [],
274
+ issuer: "issuer",
275
+ clientId: "clientId",
276
+ };
277
+ const mockedAccessToken = {
278
+ accessToken: "accessToken",
279
+ claims: mockedClaims,
280
+ tokenType: "tokenType",
281
+ userinfoUrl: "userinfo.url",
282
+ expiresAt: Date.now(),
283
+ authorizeUrl: "authorize.url",
284
+ scopes: [],
285
+ };
286
+ const mockedAuthState = {
287
+ accessToken: mockedAccessToken,
288
+ idToken: mockedIdToken,
289
+ isAuthenticated: true,
290
+ };
291
+ const mockedOktaAuth = () => {
292
+ return {
293
+ oktaAuth: {
294
+ tokenManager: {
295
+ on: jest.fn(),
296
+ renew: jest.fn(),
297
+ setTokens: jest.fn(),
298
+ clear: jest.fn(),
299
+ },
300
+ getOriginalUri: jest.fn(),
301
+ signOut: jest.fn().mockResolvedValue({ postLogoutRedirectUri: "mocked-url", clearTokensBeforeRedirect: true }),
302
+ token: {
303
+ getWithRedirect: jest.fn(),
304
+ getWithoutPrompt: jest.fn(),
305
+ },
306
+ session: {
307
+ get: () => {
308
+ return { status: "ACTIVE" };
309
+ },
310
+ },
311
+ authStateManager: {
312
+ getAuthState: jest.fn(),
313
+ subscribe: jest.fn(),
314
+ unsubscribe: jest.fn(),
315
+ },
316
+ closeSession: jest.fn(),
317
+ options: {
318
+ restoreOriginalUri: "",
319
+ },
320
+ start: jest.fn(),
321
+ setOriginalUri: jest.fn(),
322
+ },
323
+ authState: mockedAuthState,
324
+ };
325
+ };
326
+ // This ensures its being mocked in jest.
327
+ jest.mock("@okta/okta-react", () => {
328
+ return {
329
+ useOktaAuth: () => mockedOktaAuth(),
330
+ };
331
+ });
332
+ };
333
+ jest.mock("highcharts/modules/boost", () => jest.fn());
334
+
335
+ /**
336
+ * Mocks the react-virtualized-auto-sizer component for testing environments.
337
+ *
338
+ * This function creates a mock implementation of the AutoSizer component from
339
+ * react-virtualized-auto-sizer, which is commonly used to measure and adapt to
340
+ * container dimensions. Instead of actual dimension measurements, the mock provides
341
+ * fixed dimensions (600x600), allowing tests to run consistently without actual DOM measuring.
342
+ *
343
+ * This is especially useful for testing components that use virtualized lists or grids,
344
+ * as it eliminates the need for setting up complex DOM environments just to get measurements.
345
+ *
346
+ * @example
347
+ * // In your jest setup file
348
+ * import { setupReactVirtualizedAutoSizer } from '@trackunit/react-test-setup';
349
+ *
350
+ * setupReactVirtualizedAutoSizer();
351
+ */
352
+ const setupReactVirtualizedAutoSizer = () => {
353
+ jest.mock("react-virtualized-auto-sizer", () => ({ children }) => children({ height: 600, width: 600, scaledWidth: 600, scaledHeight: 600 }));
354
+ };
355
+
356
+ /**
357
+ * Mock the ResizeObserver to be able to test components that use a resize observer
358
+ * Like useGeometry, useContainerBreakpoints, etc.
359
+ * Also componets that _use_ useGeometry, like <BaseInput/> and many more
360
+ *
361
+ * Recommended for all react libs
362
+ */
363
+ const setupResizeObserver = () => {
364
+ global.ResizeObserver = jest.fn().mockImplementation((callback) => ({
365
+ observe: jest.fn(),
366
+ unobserve: jest.fn(),
367
+ disconnect: jest.fn(),
368
+ }));
369
+ };
370
+
371
+ /**
372
+ * Mocks the @tanstack/react-virtual library for testing environments.
373
+ *
374
+ * This function creates a mock implementation of the useVirtualizer hook from
375
+ * the @tanstack/react-virtual library, which is used for efficiently rendering
376
+ * large lists and grids. The mock returns a simplified version that generates
377
+ * virtual items with deterministic sizes and provides all expected methods.
378
+ *
379
+ * Each virtual item has:
380
+ * - A consistent height (40px)
381
+ * - Index and key properties matching the item's position
382
+ * - Empty implementation of the measureRef function
383
+ *
384
+ * This allows for testing components that use virtualized lists without requiring
385
+ * actual DOM measurements or complex setup.
386
+ *
387
+ * @example
388
+ * // In your jest setup file
389
+ * import { setupTanstackReactVirtual } from '@trackunit/react-test-setup';
390
+ *
391
+ * setupTanstackReactVirtual();
392
+ */
393
+ const setupTanstackReactVirtual = () => {
394
+ jest.mock("@tanstack/react-virtual", () => ({
395
+ useVirtualizer: ({ count }) => ({
396
+ getVirtualItems: () => {
397
+ const result = [];
398
+ for (let i = 0; i < count; i++) {
399
+ result.push({ index: i, start: i * 40, key: i, measureRef: () => { } });
400
+ }
401
+ return result;
402
+ },
403
+ getTotalSize: () => count,
404
+ scrollToIndex: () => { },
405
+ scrollToOffset: () => { },
406
+ scrollToAlign: () => { },
407
+ scrollToItem: () => { },
408
+ resetAfterIndex: () => { },
409
+ resetAfterItem: () => { },
410
+ scrollTo: () => { },
411
+ measure: () => { },
412
+ }),
413
+ }));
414
+ };
415
+
416
+ /* eslint-disable @typescript-eslint/no-explicit-any */
417
+ /**
418
+ * Mocks the Temporal API to use a fixed time zone for testing.
419
+ *
420
+ * This function specifically mocks the Temporal.Now.timeZoneId method from the
421
+ * Temporal library to always return "Europe/Copenhagen", ensuring consistent
422
+ * time zone-dependent behavior in tests regardless of where they run.
423
+ *
424
+ * @example
425
+ * // In your jest setup file
426
+ * import { setupTimeZone } from '@trackunit/react-test-setup';
427
+ *
428
+ * setupTimeZone();
429
+ */
430
+ const setupTimeZone = () => {
431
+ jest.spyOn(Temporal.Now, "timeZoneId").mockImplementation(() => "Europe/Copenhagen");
432
+ };
433
+ /**
434
+ * Sets up time, animation, and language-related mocks for testing environments.
435
+ *
436
+ * This function configures multiple aspects of the testing environment:
437
+ * 1. Sets a fixed time zone using setupTimeZone()
438
+ * 2. Disables React Spring animations for faster, deterministic tests
439
+ * 3. Mocks the useDebounce hook to immediately return values without delays
440
+ * 4. Overrides setTimeout and setInterval to execute immediately (0ms delay)
441
+ *
442
+ * These changes make tests faster and more predictable by eliminating real-time
443
+ * delays, animations, and time zone dependencies that could cause flaky tests.
444
+ *
445
+ * @example
446
+ * // In your jest setup file
447
+ * import { setupTimeAndLanguage } from '@trackunit/react-test-setup';
448
+ *
449
+ * setupTimeAndLanguage();
450
+ */
451
+ const setupTimeAndLanguage = () => {
452
+ setupTimeZone();
453
+ Globals.assign({
454
+ skipAnimation: true,
455
+ });
456
+ jest.mock("@trackunit/react-components", () => ({
457
+ ...jest.requireActual("@trackunit/react-components"),
458
+ useDebounce: (value) => value,
459
+ }));
460
+ const globalSetTimeout = global.setTimeout;
461
+ global.ORG_setTimeout = globalSetTimeout;
462
+ const globalSetInterval = global.setInterval;
463
+ global.ORG_setInterval = globalSetInterval;
464
+ global.setTimeout = function testSetTimeout(callback, ms, ...args) {
465
+ return globalSetTimeout.apply(this, [callback, 0]);
466
+ };
467
+ global.setInterval = function testSetInterval(callback, ms, ...args) {
468
+ return globalSetInterval.apply(this, [callback, 0]);
469
+ };
470
+ };
471
+
472
+ /**
473
+ * Sets up internationalization and translation mocks for testing environments.
474
+ *
475
+ * This function delegates to the implementation in setupTranslationsImpl.tsx to configure
476
+ * mock translations for react-i18next and @trackunit/i18n-library-translation. It creates
477
+ * simple mock implementations that return the key string as the translation, which allows
478
+ * for testing internationalized components without the complexity of actual translations.
479
+ *
480
+ * The mocks support common translation components and hooks like Trans, useTranslation,
481
+ * NamespaceTrans, and useNamespaceTranslation.
482
+ *
483
+ * @example
484
+ * // In your jest setup file
485
+ * import { setupTranslations } from '@trackunit/react-test-setup';
486
+ *
487
+ * setupTranslations();
488
+ */
489
+ const setupTranslations = () => {
490
+ // eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports
491
+ require("./setupTranslationsImpl").setupTranslations();
492
+ };
493
+
494
+ /**
495
+ * Sets up Web Streams API polyfills for testing environments.
496
+ *
497
+ * This function delegates to the implementation in setupWebStreamsImpl.ts to configure
498
+ * Web Streams API polyfills from web-streams-polyfill. These polyfills provide implementations
499
+ * of modern streaming APIs that may not be available in the Jest/JSDOM testing environment.
500
+ *
501
+ * The setup enables testing of components and utilities that rely on the Web Streams API,
502
+ * such as those that process streaming data or implement custom stream transformations.
503
+ *
504
+ * @example
505
+ * // In your jest setup file
506
+ * import { setupWebStreams } from '@trackunit/react-test-setup';
507
+ *
508
+ * setupWebStreams();
509
+ */
510
+ const setupWebStreams = () => {
511
+ // eslint-disable-next-line @typescript-eslint/no-var-requires, @typescript-eslint/no-require-imports
512
+ require("./setupWebStreamsImpl").setupWebStreams();
513
+ };
514
+
515
+ /**
516
+ * Sets up all available testing mocks in a single function call.
517
+ *
518
+ * This convenience function sets up all the test mocks provided by the library:
519
+ * - Canvas API mocks
520
+ * - Console error reporting to fail tests
521
+ * - Google Maps API and components mocks
522
+ * - React Helmet mocks
523
+ * - IntersectionObserver mocks
524
+ * - MatchMedia API mocks
525
+ * - React Testing Library and Okta authentication mocks
526
+ * - React Virtualized AutoSizer mocks
527
+ * - ResizeObserver mocks
528
+ * - Tanstack React Virtual mocks
529
+ * - Time and language related mocks (timezone, timers, etc.)
530
+ * - Translation mocks (i18n)
531
+ * - Web Streams API mocks
532
+ *
533
+ * Using this function is equivalent to calling each setup function individually.
534
+ *
535
+ * @param options Configuration options for individual mocks
536
+ * @param options.failOnConsoleOptions Options for setupFailOnConsole
537
+ * @example
538
+ * // In your jest setup file
539
+ * import { setupAllMocks } from '@trackunit/react-test-setup';
540
+ *
541
+ * setupAllMocks();
542
+ *
543
+ * // Or with options for specific mocks:
544
+ * setupAllMocks({
545
+ * failOnConsoleOptions: { shouldFailOnWarn: true }
546
+ * });
547
+ */
548
+ const setupAllMocks = (options = {}) => {
549
+ setupCanvasMock();
550
+ setupFailOnConsole(options.failOnConsoleOptions);
551
+ setupGoogleMaps();
552
+ setupHelmetMock();
553
+ setupIntersectionObserver();
554
+ setupMatchMediaMock();
555
+ setupReactTestingLibrary();
556
+ setupReactVirtualizedAutoSizer();
557
+ setupResizeObserver();
558
+ setupTanstackReactVirtual();
559
+ setupTimeAndLanguage();
560
+ setupTranslations();
561
+ setupWebStreams();
562
+ };
563
+
564
+ /**
565
+ * Sets up essential testing mocks that don't have external library dependencies.
566
+ *
567
+ * This convenience function configures a minimal set of test mocks that are broadly
568
+ * applicable for most React testing scenarios without requiring specific external
569
+ * libraries. It includes:
570
+ *
571
+ * - Canvas API mocks
572
+ * - Console error reporting to fail tests
573
+ * - IntersectionObserver mocks
574
+ * - MatchMedia API mocks
575
+ * - ResizeObserver mocks
576
+ * - Timer mocks (setTimeout, setInterval)
577
+ * - Web Streams API mocks
578
+ *
579
+ * This is perfect for projects that want essential testing mocks without bringing
580
+ * in dependencies for libraries they don't use like Google Maps, React Virtual, etc.
581
+ *
582
+ * @param options Configuration options for individual mocks
583
+ * @param options.failOnConsoleOptions Options for setupFailOnConsole
584
+ * @example
585
+ * // In your jest setup file
586
+ * import { setupBasicMocks } from '@trackunit/react-test-setup';
587
+ *
588
+ * setupBasicMocks();
589
+ *
590
+ * // Or with options for specific mocks:
591
+ * setupBasicMocks({
592
+ * failOnConsoleOptions: { shouldFailOnWarn: true }
593
+ * });
594
+ */
595
+ /**
596
+ * Sets up essential testing mocks with no external library dependencies.
597
+ *
598
+ * @param options Configuration options for the mocks
599
+ */
600
+ const setupBasicMocks = (options = {}) => {
601
+ // Core DOM and browser APIs
602
+ setupCanvasMock();
603
+ setupIntersectionObserver();
604
+ setupMatchMediaMock();
605
+ setupResizeObserver();
606
+ setupWebStreams();
607
+ // Time and error handling
608
+ setupTimeAndLanguage();
609
+ setupFailOnConsole(options.failOnConsoleOptions);
610
+ };
611
+
612
+ /**
613
+ * Sets up default testing mocks that cover most common React testing needs.
614
+ *
615
+ * This convenience function provides a balanced set of mocks that cover most React
616
+ * application testing needs. It includes all the basic mocks plus essential React
617
+ * testing utilities. Specifically, it includes:
618
+ *
619
+ * From setupBasicMocks:
620
+ * - Canvas API mocks
621
+ * - Console error reporting to fail tests
622
+ * - IntersectionObserver mocks
623
+ * - MatchMedia API mocks
624
+ * - ResizeObserver mocks
625
+ * - Timer mocks (setTimeout, setInterval)
626
+ * - Web Streams API mocks
627
+ *
628
+ * Plus these additional mocks:
629
+ * - React Testing Library and Okta authentication mocks
630
+ * - Translation mocks (i18n)
631
+ *
632
+ * This is ideal for most React applications that use i18n translations and need
633
+ * standard testing environment setup, without requiring specialized mocks for things
634
+ * like Google Maps or virtualized lists.
635
+ *
636
+ * @param options Configuration options for individual mocks
637
+ * @param options.failOnConsoleOptions Options for setupFailOnConsole
638
+ * @example
639
+ * // In your jest setup file
640
+ * import { setupDefaultMocks } from '@trackunit/react-test-setup';
641
+ *
642
+ * setupDefaultMocks();
643
+ *
644
+ * // Or with options for specific mocks:
645
+ * setupDefaultMocks({
646
+ * failOnConsoleOptions: { shouldFailOnWarn: true }
647
+ * });
648
+ */
649
+ /**
650
+ * Sets up default testing mocks covering most common React testing scenarios.
651
+ *
652
+ * @param options Configuration options for the mocks
653
+ */
654
+ const setupDefaultMocks = (options = {}) => {
655
+ // Set up all basic mocks first
656
+ setupBasicMocks(options);
657
+ // Add standard React testing utilities
658
+ setupReactTestingLibrary();
659
+ setupTranslations();
660
+ };
661
+
662
+ export { setupAllMocks, setupBasicMocks, setupCanvasMock, setupDefaultMocks, setupFailOnConsole, setupGoogleMaps, setupHelmetMock, setupIntersectionObserver, setupMatchMediaMock, setupReactTestingLibrary, setupReactVirtualizedAutoSizer, setupResizeObserver, setupTanstackReactVirtual, setupTimeAndLanguage, setupTimeZone, setupTranslations, setupWebStreams };
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@trackunit/react-test-setup",
3
+ "description": "Test setup utilities for React applications",
4
+ "version": "1.0.0",
5
+ "repository": "https://github.com/Trackunit/manager",
6
+ "license": "SEE LICENSE IN LICENSE.txt",
7
+ "engines": {
8
+ "node": ">=22.x"
9
+ },
10
+ "dependencies": {
11
+ "@googlemaps/jest-mocks": "2.21.4",
12
+ "@js-temporal/polyfill": "^0.4.4",
13
+ "@okta/okta-auth-js": "^7.8.1",
14
+ "@react-spring/web": "9.7.5",
15
+ "@testing-library/jest-dom": "^6.6.3",
16
+ "@testing-library/react": "16.2.0",
17
+ "@vis.gl/react-google-maps": "^0.4.2",
18
+ "jest-canvas-mock": "^2.5.2",
19
+ "jest-fail-on-console": "^3.1.1",
20
+ "react": "19.0.0",
21
+ "react-i18next": "^15.5.1",
22
+ "react-virtualized-auto-sizer": "^1.0.20",
23
+ "web-streams-polyfill": "^4.1.0"
24
+ },
25
+ "module": "./index.esm.js",
26
+ "main": "./index.cjs.js",
27
+ "types": "./index.esm.d.ts"
28
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ export * from "./setupAllMocks";
2
+ export * from "./setupBasicMocks";
3
+ export * from "./setupDefaultMocks";
4
+ export * from "./setupCanvasMock";
5
+ export * from "./setupFailOnConsole";
6
+ export * from "./setupGoogleMaps";
7
+ export * from "./setupHelmetMock";
8
+ export * from "./setupIntersectionObserver";
9
+ export * from "./setupMatchMediaMock";
10
+ export * from "./setupReactTestingLibrary";
11
+ export * from "./setupReactVirtualizedAutoSizer";
12
+ export * from "./setupResizeObserver";
13
+ export * from "./setupTanstackReactVirtualize";
14
+ export * from "./setupTimeAndLanguage";
15
+ export * from "./setupTranslations";
16
+ export * from "./setupWebStreams";