@trackunit/react-core-contexts-test 1.7.80 → 1.7.83

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.cjs.js CHANGED
@@ -1,1377 +1,40 @@
1
1
  'use strict';
2
2
 
3
- var reactCoreContextsApi = require('@trackunit/react-core-contexts-api');
4
- var jsxRuntime = require('react/jsx-runtime');
5
- var react$1 = require('@testing-library/react');
6
- var reactCoreHooks = require('@trackunit/react-core-hooks');
7
- var esToolkit = require('es-toolkit');
8
- var client = require('@apollo/client');
9
- var dev = require('@apollo/client/dev');
10
- var error = require('@apollo/client/link/error');
11
- var testing = require('@apollo/client/testing');
12
- var sharedUtils = require('@trackunit/shared-utils');
13
- var React = require('react');
14
- var react = require('@apollo/client/react');
15
- var reactRouter = require('@tanstack/react-router');
16
- var graphql = require('graphql');
17
-
18
- /**
19
- * Do nothing
20
- */
21
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
22
- const doNothing = () => {
23
- /* Do nothing */
24
- };
25
-
26
- const mockAnalyticsContext = {
27
- logEvent: doNothing,
28
- logError: doNothing,
29
- logPageView: doNothing,
30
- setUserProperty: doNothing,
31
- };
32
-
33
- const mockAssetSortingContext = {
34
- setSortBy: doNothing,
35
- sortingState: {
36
- sortBy: reactCoreContextsApi.AssetSortByProperty.Criticality,
37
- order: reactCoreContextsApi.SortOrder.Desc,
38
- },
39
- };
40
-
41
- /**
42
- * Mocks the current user context
43
- *
44
- * @returns {CurrentUserContextInterface} - Returns the mocked current user context
45
- */
46
- const mockCurrentUserContext = {
47
- clientSideUserId: "751ea227-f199-4d00-925f-a608312c5e45",
48
- userName: "",
49
- userRole: "",
50
- customerId: 12345,
51
- userId: 154312,
52
- tasUserId: "751ea227-f199-4d00-925f-a608312c5e45",
53
- email: "",
54
- name: "",
55
- accountId: "",
56
- assumedUser: null,
57
- jobTitle: "",
58
- isAuthenticated: true,
59
- isVerified: true,
60
- isTrackunitUser: false,
61
- isAssuming: false,
62
- isAccountOwner: true,
63
- };
64
-
65
- const mockEnvironmentContext = {
66
- auth: {
67
- url: "",
68
- clientId: "",
69
- issuer: "",
70
- },
71
- managerClassicUrl: "https://sso.trackunit.com",
72
- googleMapsApiKey: "",
73
- amplitudeApiKey: "",
74
- amplitudeApiEndpoint: "",
75
- graphqlPublicUrl: "",
76
- graphqlInternalUrl: "",
77
- graphqlReportUrl: "",
78
- buildVersion: "",
79
- commitNumber: 0,
80
- irisAppSdkServerUrl: "",
81
- publicUrl: "",
82
- isFeatureBranch: false,
83
- environment: "dev",
84
- sentryDsn: "",
85
- sessionId: "",
86
- tracingHeaders: {
87
- "X-TrackunitAppVersion": "",
88
- "session-id": "",
89
- "commit-number": 0,
90
- },
91
- trackunitRestApiUrl: "",
92
- hubspotRequestAppAccessFormId: "",
93
- uptimeId: "",
94
- reportAccessCallback: "",
95
- reportAccessClientId: "",
96
- };
97
-
98
- /**
99
- * This is a mock for the FilterBarContext.
100
- *
101
- * @returns { FilterBarContext }- mock for the FilterBarContext
102
- */
103
- const mockFilterBarContext = {
104
- assetsFilterBarValues: {},
105
- customersFilterBarValues: {},
106
- sitesFilterBarValues: {},
107
- isLoading: false,
108
- };
109
-
110
- const mockOemBrandingContext = {
111
- getAllBrandingDetails: doNothing,
112
- getOemBranding: async () => null,
113
- getOemImage: doNothing,
114
- };
115
-
116
- const mockToastContext = {
117
- addToast: doNothing,
118
- removeToast: doNothing,
119
- setIsManifestError: doNothing,
120
- };
121
-
122
- /**
123
- * This is a mock for the UserSubscriptionContext.
124
- *
125
- * @returns { IUserSubscriptionContext }- mock for the UserSubscriptionContext
126
- */
127
- const mockUserSubscriptionContext = {
128
- numberOfDaysWithAccessToHistoricalData: 30,
129
- numberOfDaysWithAccessToHistoricalInsights: 30,
130
- features: [],
131
- loading: false,
132
- packageType: "EXPAND_FLEET_OWNER",
133
- };
134
-
135
- const defaultOptions = {
136
- mutate: {
137
- errorPolicy: "all",
138
- },
139
- query: {
140
- errorPolicy: "all",
141
- },
142
- };
143
- /**
144
- * This is a wrapper around the MockedProvider that logs errors to the console.
145
- */
146
- function ApolloMockedProviderWithError(props) {
147
- const isDebugging = !!process.env.VSCODE_INSPECTOR_OPTIONS || !!process.env.DEBUG;
148
- dev.loadDevMessages();
149
- dev.loadErrorMessages();
150
- const { mocks, ...otherProps } = props;
151
- const mockLink = new testing.MockLink(mocks, false, { showWarnings: isDebugging });
152
- const errorLoggingLink = error.onError(({ graphQLErrors, networkError }) => {
153
- if (graphQLErrors) {
154
- graphQLErrors.map(({ message, locations, path }) => {
155
- if (isDebugging) {
156
- // eslint-disable-next-line no-console
157
- console.log(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`);
158
- }
159
- });
160
- }
161
- if (networkError && isDebugging) {
162
- // eslint-disable-next-line no-console
163
- console.log(`[Network error]: ${networkError}`);
164
- }
165
- });
166
- const link = client.ApolloLink.from([errorLoggingLink, mockLink]);
167
- return (jsxRuntime.jsx(testing.MockedProvider, { ...otherProps, defaultOptions: { ...defaultOptions, watchQuery: { fetchPolicy: "no-cache" } }, link: link }));
168
- }
169
-
170
- const mockConfirmationDialogContext = {
171
- confirm: doNothing,
172
- };
173
-
174
- /**
175
- * Mocks the current user context
176
- *
177
- * @returns {IUserPreferencesContext} - Returns the mocked current user context
178
- */
179
- const mockCurrentUserPreferenceContext = {
180
- language: "en",
181
- setLanguage: doNothing,
182
- timeZonePreference: "LOCAL_TIME_ZONE",
183
- setTimeZonePreference: doNothing,
184
- systemOfMeasurement: "SI",
185
- setSystemOfMeasurement: doNothing,
186
- };
187
-
188
- const mockExportDataContextState = {
189
- exportData: () => Promise.resolve(),
190
- };
191
-
192
- /**
193
- * Mocks the ErrorHandlingContextValue
194
- *
195
- * @returns {ErrorHandlingContextValue} - Returns the mocked current user context
196
- */
197
- const mockErrorHandlerContext = {
198
- captureException: sharedUtils.doNothing,
199
- addBreadcrumb: sharedUtils.doNothing,
200
- setTag: sharedUtils.doNothing,
201
- };
202
-
203
- const mockModalDialogContext = {
204
- openModal: doNothing,
205
- closeModal: doNothing,
206
- };
207
-
208
- const mockNavigationContext = {
209
- hasAccessTo: (options) => {
210
- return Promise.resolve(true);
211
- },
212
- gotoAssetHome: (assetId, options) => {
213
- return Promise.resolve(true);
214
- },
215
- gotoSiteHome: (siteId, options) => {
216
- return Promise.resolve(true);
217
- },
218
- gotoGroupHome: (groupId, options) => {
219
- return Promise.resolve(true);
220
- },
221
- gotoAppLibrary: (irisAppId) => {
222
- return Promise.resolve(true);
223
- },
224
- gotoFleetApp: (options) => {
225
- return Promise.resolve(true);
226
- },
227
- gotoCustomerHome: (customerId) => {
228
- return Promise.resolve(true);
229
- },
230
- gotoAdmin: (url) => {
231
- return Promise.resolve(true);
232
- },
233
- gotoAlerts: (url) => {
234
- return Promise.resolve(true);
235
- },
236
- gotoMarketplace: () => {
237
- return Promise.resolve(true);
238
- },
239
- reloadManager: () => {
240
- return Promise.resolve(true);
241
- },
242
- getAssetHomeUrl: (assetId, options) => {
243
- return Promise.resolve(`/assets/${assetId}/status`);
244
- },
245
- getSiteHomeUrl: (siteId, options) => {
246
- return Promise.resolve(`/sites/${siteId}/overview`);
247
- },
248
- getGroupHomeUrl: (groupId, options) => {
249
- return Promise.resolve(`/groups/${groupId}/home`);
250
- },
251
- getCustomerHomeUrl: (customerId, options) => {
252
- return Promise.resolve(customerId ? `/customers/${customerId}/info` : `/customers`);
253
- },
254
- getAppLibraryUrl: irisAppId => {
255
- return Promise.resolve(`/administration/app-library`);
256
- },
257
- getFleetAppUrl: options => {
258
- return Promise.resolve(`/fleet`);
259
- },
260
- getAdminUrl: url => {
261
- return Promise.resolve(url ? `/administration${url}` : `/administration`);
262
- },
263
- getAlertsUrl: url => {
264
- return Promise.resolve(url ? `/event-setup${url}` : `/event-setup`);
265
- },
266
- getMarketplaceUrl: options => {
267
- return Promise.resolve(`/marketplace`);
268
- },
269
- };
270
-
271
- const mockTimeRangeContext = {
272
- timeRange: {
273
- startMsInEpoch: 1,
274
- endMsInEpoch: 2,
275
- },
276
- temporalPeriod: {
277
- direction: "last",
278
- count: 3,
279
- unit: "days",
280
- },
281
- };
282
-
283
- const mockWidgetConfigContext = {
284
- pollInterval: 1000,
285
- getTitle: async () => "Test Title",
286
- setTitle: async () => { },
287
- getData: async () => ({}),
288
- getDataVersion: async () => 1,
289
- setData: async () => { },
290
- setLoadingState: async () => { },
291
- openEditMode: async () => { },
292
- closeEditMode: async () => { },
293
- };
294
-
295
- const RerenderContext = React.createContext({ rerenderCounter: 0, setRerenderCounter: (value) => { } });
296
- /**
297
- * This provider is used to force re-renders in the test environment, since tanstack router does not support re-render.
298
- */
299
- const RerenderProvider = ({ children, counter }) => {
300
- const [rerenderCounter, setRerenderCounter] = React.useState(0);
301
- React.useEffect(() => {
302
- if (counter && rerenderCounter !== counter && rerenderCounter !== 0) {
303
- setRerenderCounter(counter);
304
- }
305
- }, [rerenderCounter, counter]);
306
- return (jsxRuntime.jsx(RerenderContext.Provider, { value: { rerenderCounter, setRerenderCounter }, children: children }));
307
- };
308
- /**
309
- * This hook is used to get the rerender counter.
310
- */
311
- const useRerenderCounter = () => {
312
- return React.useContext(RerenderContext);
313
- };
314
-
315
- /**
316
- * This component is used to force re-renders in the test environment, since tanstack router does not support re-render.
317
- */
318
- const RerenderComponent = ({ children }) => {
319
- const { rerenderCounter } = useRerenderCounter();
320
- return (jsxRuntime.jsx("div", { "data-rerender-counter": `rerender-${rerenderCounter}`, children: React.Children.map(children, child => React.isValidElement(child)
321
- ? React.createElement(child.type, {
322
- ...child.props,
323
- key: child.key,
324
- "data-rerender-counter": rerenderCounter,
325
- })
326
- : child) }));
327
- };
328
-
329
- const buildFlatRouteMap = (routes) => {
330
- const routeMap = {};
331
- routes.forEach(route => {
332
- routeMap[route.id] = route;
333
- if (Array.isArray(route.children)) {
334
- Object.assign(routeMap, buildFlatRouteMap(route.children));
335
- }
336
- });
337
- return routeMap;
338
- };
339
- /**
340
- * This component is used to wrap the children of the RouterContainer to add a test root container
341
- */
342
- const RootRouteDebugger = () => {
343
- // const matches = useMatches();
344
- // console.log(
345
- // "matches",
346
- // matches.map(match => match.routeId)
347
- // );
348
- return jsxRuntime.jsx(reactRouter.Outlet, {});
349
- };
350
- /**
351
- * This component is used to wrap the children of the RouterContainer to add a test root container.
352
- *
353
- * @param addTestRootContainer boolean to add test root container
354
- * @param children children to be wrapped
355
- * @returns {ReactNode} children component wrapped in a test root container
356
- */
357
- const TestRenderChildren = ({ addTestRootContainer, children }) => {
358
- return addTestRootContainer ? (jsxRuntime.jsx("div", { className: "inline-block h-[1000px] w-[1024px] scale-[.99]", "data-testid": "testRoot", style: {
359
- "--tw-scale-x": "0.99",
360
- "--tw-scale-y": "0.99",
361
- }, children: children })) : (jsxRuntime.jsx("div", { children: children }));
362
- };
363
- /**
364
- * This component is used to wrap the children of the RouterContainer to add a test root container.
365
- *
366
- * @param addTestRootContainer boolean to add test root container
367
- * @param selectedRouterProps selected router props
368
- * @param rootRoute root route
369
- * @param children children to be wrapped
370
- * @returns {ReactElement} children component wrapped in a test root container
371
- */
372
- const RouterContainer = ({ addTestRootContainer, selectedRouterProps, rootRoute, children, }) => {
373
- const client = react.useApolloClient();
374
- // The current version of createMemoryHistory seem to have issues when NOT ending on / so adding a # will not effect what url is rendered but it seems to work
375
- const memoryHistory = React.useRef(reactRouter.createMemoryHistory({
376
- initialEntries: selectedRouterProps?.initialEntries?.reverse().map(entry => entry.path + "#") ?? ["/#"],
377
- initialIndex: 0,
378
- }));
379
- const addTestRootContainerRef = React.useRef(addTestRootContainer);
380
- React.useEffect(() => {
381
- addTestRootContainerRef.current = addTestRootContainer;
382
- }, [addTestRootContainer]);
383
- const getChildren = React.useCallback(() => children, [children]);
384
- const childrenRef = React.useRef(() => getChildren());
385
- React.useEffect(() => {
386
- childrenRef.current = () => getChildren();
387
- }, [getChildren]);
388
- const initialEntriesRef = React.useRef(selectedRouterProps?.initialEntries);
389
- React.useEffect(() => {
390
- initialEntriesRef.current = selectedRouterProps?.initialEntries;
391
- }, [selectedRouterProps?.initialEntries]);
392
- const router = React.useMemo(() => {
393
- let localRootRoute = rootRoute;
394
- if (!localRootRoute) {
395
- const route = reactRouter.createRootRoute({ component: RootRouteDebugger });
396
- const childRoute = reactRouter.createRoute({
397
- path: "/",
398
- getParentRoute: () => route,
399
- component: () => {
400
- return (jsxRuntime.jsx(TestRenderChildren, { addTestRootContainer: addTestRootContainerRef.current, children: childrenRef.current() }));
401
- },
402
- });
403
- route.addChildren([childRoute]);
404
- localRootRoute = route;
405
- }
406
- else {
407
- const pathsToRoute = buildFlatRouteMap([localRootRoute]);
408
- sharedUtils.objectValues(pathsToRoute).forEach(route => {
409
- route.options.component = RootRouteDebugger;
410
- route.lazyFn = undefined;
411
- });
412
- if (pathsToRoute.__root__) {
413
- pathsToRoute.__root__.options.component = RootRouteDebugger;
414
- pathsToRoute.__root__.options.beforeLoad = () => { };
415
- pathsToRoute.__root__.lazyFn = undefined;
416
- }
417
- if (pathsToRoute["/"]) {
418
- // This ensures / is not redirecting to default home route
419
- pathsToRoute["/"].options.beforeLoad = () => { };
420
- }
421
- if ((initialEntriesRef.current?.length || 0) > 0) {
422
- initialEntriesRef.current?.forEach(entry => {
423
- const route = pathsToRoute[entry.route];
424
- if (route) {
425
- if (entry.beforeLoad) {
426
- route.options.beforeLoad = entry.beforeLoad;
427
- }
428
- if (entry.component) {
429
- route.options.component = entry.component;
430
- }
431
- else {
432
- route.update({
433
- component: () => {
434
- return (jsxRuntime.jsx(TestRenderChildren, { addTestRootContainer: addTestRootContainerRef.current, children: childrenRef.current() }));
435
- },
436
- });
437
- }
438
- }
439
- });
440
- }
441
- else {
442
- const slashRoute = pathsToRoute["/"];
443
- if (slashRoute) {
444
- slashRoute.options.component = () => (jsxRuntime.jsx(TestRenderChildren, { addTestRootContainer: addTestRootContainerRef.current, children: childrenRef.current() }));
445
- }
446
- else {
447
- const childRoute = reactRouter.createRoute({
448
- path: "/",
449
- getParentRoute: () => localRootRoute,
450
- component: () => {
451
- return (jsxRuntime.jsx(TestRenderChildren, { addTestRootContainer: addTestRootContainerRef.current, children: childrenRef.current() }));
452
- },
453
- });
454
- localRootRoute.addChildren([childRoute]);
455
- }
456
- }
457
- }
458
- return reactRouter.createRouter({
459
- routeTree: localRootRoute,
460
- history: memoryHistory.current,
461
- defaultPendingMs: 0,
462
- defaultPendingMinMs: 0, // Add this to control minimum pending time
463
- context: {
464
- hasAccessTo: async () => {
465
- return true;
466
- },
467
- showMarketplace: true,
468
- showHelpCenter: true,
469
- showAppLibrary: true,
470
- client: null,
471
- defaultUserRoute: "/",
472
- isAuthenticated: true,
473
- },
474
- });
475
- }, [rootRoute]);
476
- const context = React.useMemo(() => ({
477
- hasAccessTo: async () => true,
478
- isAuthenticated: true,
479
- client,
480
- defaultUserRoute: "/",
481
- ...(selectedRouterProps?.context || {}),
482
- }), [client, selectedRouterProps?.context]);
483
- const ErrorComponent = ({ error }) => {
484
- return jsxRuntime.jsxs(jsxRuntime.Fragment, { children: ["UNCAUGHT ERROR IN TEST: ", error instanceof Error ? error.message : error] });
485
- };
486
- return jsxRuntime.jsx(reactRouter.RouterProvider, { context: context, defaultErrorComponent: ErrorComponent, router: router });
487
- };
488
-
489
- /**
490
- * Flushes all promises in the queue.
491
- * This is useful when testing async code.
492
- *
493
- * @param waitTimeInMS - The amount of time to wait before resolving the promise.
494
- * @returns {Promise<void>} - Returns a promise that resolves after the wait time.
495
- */
496
- const flushPromises = (waitTimeInMS = 0) => {
497
- return new Promise(resolve => {
498
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
499
- if (global.ORG_setTimeout) {
500
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
501
- return global.ORG_setTimeout(() => global.ORG_setTimeout(resolve, waitTimeInMS), 1);
502
- }
503
- else {
504
- setTimeout(() => setTimeout(resolve, waitTimeInMS), 1);
505
- }
506
- });
507
- };
508
- /**
509
- * Flushes all promises in the queue.
510
- * This is useful when testing async code.
511
- *
512
- * @param waitTimeInMS - The amount of time to wait before resolving the promise.
513
- * @returns {Promise<void>} - Returns a promise that resolves after the wait time.
514
- */
515
- const flushPromisesInAct = (waitTimeInMS = 0) => {
516
- return react$1.act(() => {
517
- return new Promise(resolve => {
518
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
519
- if (global.ORG_setTimeout) {
520
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
521
- return global.ORG_setTimeout(() => global.ORG_setTimeout(resolve, waitTimeInMS), 1);
522
- }
523
- else {
524
- setTimeout(() => setTimeout(resolve, waitTimeInMS), 1);
525
- }
526
- });
527
- });
528
- };
529
-
530
- /**
531
- * This builder allows you to enable trackunit providers using the builder pattern, and then call 1 of either:
532
- * For React Components:
533
- * - render
534
- * For React Hooks:
535
- * - renderHook
536
- * For Storybook:
537
- * - storybook
538
- */
539
- class TrackunitProvidersMockBuilder {
540
- constructor() {
541
- this.selectedEnvironmentContext = mockEnvironmentContext;
542
- this.selectedModalDialogContext = mockModalDialogContext;
543
- this.selectedTimeRangeContext = mockTimeRangeContext;
544
- this.selectedWidgetConfigContext = mockWidgetConfigContext;
545
- this.selectedNavigationContext = mockNavigationContext;
546
- this.selectedTokenContext = { token: "fakeToken" };
547
- this.selectedApolloMocks = [];
548
- this.selectedRouterProps = null;
549
- this.selectedToastContext = mockToastContext;
550
- this.selectedErrorHandler = mockErrorHandlerContext;
551
- this.selectedConfirmationDialogContext = mockConfirmationDialogContext;
552
- this.selectedAssetSortingContext = mockAssetSortingContext;
553
- this.selectedCurrentUserContext = mockCurrentUserContext;
554
- this.selectedCurrentUserPreferenceContext = mockCurrentUserPreferenceContext;
555
- this.selectedAnalyticsContext = mockAnalyticsContext;
556
- this.selectedOemBrandingContext = mockOemBrandingContext;
557
- this.selectedUserSubscriptionContext = mockUserSubscriptionContext;
558
- this.selectedFilterBarValues = mockFilterBarContext;
559
- this.selectedExportDataContext = mockExportDataContextState;
560
- }
561
- /**
562
- * Use this Analytics Context.
563
- * Defaults to mockAnalyticsContext.
564
- *
565
- * This context is used by the useAnalytics hook from lib "@trackunit/react-core-hooks"
566
- *
567
- * @see mockAnalyticsContext
568
- * @example
569
- * ...
570
- * it("should allow render", async () => {
571
- * await trackunitProviders().analytics(yourPartialAnalyticsMock).render(<YourTestComponent data-testid="yourTestId" />);
572
- * expect(screen.getByTestId("yourTestId")).toBeInTheDocument();
573
- * });
574
- * ...
575
- * @example
576
- * ...
577
- * it("should allow renderHook", async () => {
578
- * const { result } = await trackunitProviders().analytics(yourPartialAnalyticsMock).renderHook(() => useYourTestHook());
579
- * expect(result.current).toEqual(anything());
580
- * });
581
- * ...
582
- * @param analyticsContext - The analytics context to use.
583
- * @returns { TrackunitProvidersMockBuilder } - The builder.
584
- */
585
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
586
- analytics(analyticsContext) {
587
- this.selectedAnalyticsContext = { ...mockAnalyticsContext, ...analyticsContext };
588
- return this;
589
- }
590
- /**
591
- * Use this Environment Context.
592
- * Defaults to mockEnvironmentContext.
593
- *
594
- * This context is used by the useEnvironment hook from lib "@trackunit/react-core-hooks"
595
- *
596
- * @see mockEnvironmentContext
597
- * @example
598
- * ...
599
- * it("should allow render", async () => {
600
- * await trackunitProviders().environment(yourPartialEnvironmentsMock).render(<YourTestComponent data-testid="yourTestId" />);
601
- * expect(screen.getByTestId("yourTestId")).toBeInTheDocument();
602
- * });
603
- * ...
604
- * @example
605
- * ...
606
- * it("should allow renderHook", async () => {
607
- * const { result } = await trackunitProviders().environment(yourPartialEnvironmentMock).renderHook(() => useYourTestHook());
608
- * expect(result.current).toEqual(anything());
609
- * });
610
- * ...
611
- * @param environmentContext - The environment context to use.
612
- * @returns { TrackunitProvidersMockBuilder } - The builder.
613
- */
614
- environment(environmentContext) {
615
- this.selectedEnvironmentContext = { ...mockEnvironmentContext, ...environmentContext };
616
- return this;
617
- }
618
- /**
619
- * Use this Time Range Context, used for myhome.
620
- * Defaults to mockTimeRangeContext.
621
- *
622
- * @see mockTimeRangeContext
623
- */
624
- timeRange(timeRangeContext) {
625
- this.selectedTimeRangeContext = { ...mockTimeRangeContext, ...timeRangeContext };
626
- return this;
627
- }
628
- /**
629
- * Use this Widget Config Context.
630
- * Defaults to mockWidgetConfigContext.
631
- *
632
- * @see mockWidgetConfigContext
633
- */
634
- widgetConfig(widgetConfigContext) {
635
- this.selectedWidgetConfigContext = { ...mockWidgetConfigContext, ...widgetConfigContext };
636
- return this;
637
- }
638
- /**
639
- * Use this Navigation Context.
640
- * Defaults to mockNavigationContext.
641
- *
642
- * @see mockNavigationContext
643
- * @example
644
- * ...
645
- * it("should allow render", async () => {
646
- * await trackunitProviders().navigation(yourPartialNavigationMock).render(<YourTestComponent data-testid="yourTestId" />);
647
- * expect(screen.getByTestId("yourTestId")).toBeInTheDocument();
648
- * });
649
- */
650
- navigation(navigationContext) {
651
- this.selectedNavigationContext = { ...mockNavigationContext, ...navigationContext };
652
- return this;
653
- }
654
- /**
655
- * Use this to pass in a differerent current user.
656
- * Defaults to mockCurrentUserContext.
657
- *
658
- * This context is used by the useCurrentUser hook from lib "@trackunit/react-core-hooks"
659
- *
660
- * @see mockCurrentUserContext
661
- * @example
662
- * ...
663
- * it("should allow render", async () => {
664
- * await trackunitProviders().currentUser(yourPartialCurrentUserMock).render(<YourTestComponent data-testid="yourTestId" />);
665
- * expect(screen.getByTestId("yourTestId")).toBeInTheDocument();
666
- * });
667
- * ...
668
- * @example
669
- * ...
670
- * it("should allow renderHook", async () => {
671
- * const { result } = await trackunitProviders().currentUser(yourPartialCurrentUserMock).renderHook(() => useYourTestHook());
672
- * expect(result.current).toEqual(anything());
673
- * });
674
- * ...
675
- * @returns { TrackunitProvidersMockBuilder } - The builder.
676
- */
677
- currentUser(currentUserContext) {
678
- this.selectedCurrentUserContext = { ...mockCurrentUserContext, ...currentUserContext };
679
- return this;
680
- }
681
- /**
682
- * Use this to pass in a differerent current user preference.
683
- * Defaults to mockCurrentUserPreferenceContext.
684
- *
685
- * This context is used by the useCurrentUserPreference hook from lib "@trackunit/react-core-hooks"
686
- *
687
- * @see mockCurrentUserPreferenceContext
688
- * @example
689
- * ...
690
- * it("should allow render", async () => {
691
- * await trackunitProviders().currentUserPreference(yourPartialCurrentUserPreferenceMock).render(<YourTestComponent data-testid="yourTestId" />);
692
- * expect(screen.getByTestId("yourTestId")).toBeInTheDocument();
693
- * });
694
- * ...
695
- * @example
696
- * ...
697
- * it("should allow renderHook", async () => {
698
- * const { result } = await trackunitProviders().currentUserPreference(yourPartialCurrentUserPreferenceMock).renderHook(() => useYourTestHook());
699
- * expect(result.current).toEqual(anything());
700
- * });
701
- * ...
702
- * @returns { TrackunitProvidersMockBuilder } - The builder.
703
- */
704
- currentUserPreference(currentUserPreferenceContext) {
705
- this.selectedCurrentUserPreferenceContext = {
706
- ...mockCurrentUserPreferenceContext,
707
- ...currentUserPreferenceContext,
708
- };
709
- return this;
710
- }
711
- /**
712
- * Use this to pass in a differerent filter bar values when working with pages with filterbar.
713
- * Defaults to { filterBarValues: {} }.
714
- *
715
- * @param filterBarValues - The filter bar values to use.
716
- * @example
717
- * ...
718
- * it("should allow render", async () => {
719
- * await trackunitProviders().filterBarValues(yourFilterBarValuesMock).render(<YourTestComponent data-testid="yourTestId" />);
720
- * expect(screen.getByTestId("yourTestId")).toBeInTheDocument();
721
- * });
722
- * ...
723
- * @example
724
- * ...
725
- * it("should allow renderHook", async () => {
726
- * const { result } = await trackunitProviders().filterBarValues(yourFilterBarValuesMock).renderHook(() => useYourTestHook());
727
- * expect(result.current).toEqual(anything());
728
- * });
729
- * ...
730
- * @returns { TrackunitProvidersMockBuilder } - The builder.
731
- */
732
- filterBarValues(filterBarValues) {
733
- this.selectedFilterBarValues = { ...this.selectedFilterBarValues, ...filterBarValues };
734
- return this;
735
- }
736
- /**
737
- * Use this to pass in a differerent current user subscription.
738
- * Defaults to mockUserSubscriptionContext.
739
- *
740
- * This context is used by the useUserSubscription hook from lib "@trackunit/react-core-hooks"
741
- *
742
- * @see mockUserSubscriptionContext
743
- * @example
744
- * ...
745
- * it("should allow render", async () => {
746
- * await trackunitProviders().userSubscription(yourPartialUserSubscriptionMock).render(<YourTestComponent data-testid="yourTestId" />);
747
- * expect(screen.getByTestId("yourTestId")).toBeInTheDocument();
748
- * });
749
- * ...
750
- * @example
751
- * ...
752
- * it("should allow renderHook", async () => {
753
- * const { result } = await trackunitProviders().userSubscription(yourPartialUserSubscriptionMock).renderHook(() => useYourTestHook());
754
- * expect(result.current).toEqual(anything());
755
- * });
756
- * ...
757
- * @returns { TrackunitProvidersMockBuilder } - The builder.
758
- */
759
- userSubscription(userSubscription) {
760
- //TODO DON'T SUPPORT THE WEIRD WAY OF PASSING FEATURES
761
- const featuresConverted = userSubscription.features?.map(f => {
762
- if (typeof f === "string") {
763
- return { id: f, name: f };
764
- }
765
- return f;
766
- }) || [];
767
- this.selectedUserSubscriptionContext = {
768
- ...mockUserSubscriptionContext,
769
- ...esToolkit.omit(userSubscription, ["features"]),
770
- features: [...(mockUserSubscriptionContext.features || []), ...featuresConverted],
771
- };
772
- return this;
773
- }
774
- /**
775
- * Set global asset sorting context.
776
- * Defaults to mockAssetSortingContext.
777
- *
778
- * This context is used by the useAssetSorting hook from lib "@trackunit/react-core-hooks"
779
- *
780
- * @see mockAssetSortingContext
781
- * @example
782
- * ...
783
- * it("should allow render", async () => {
784
- * await trackunitProviders().assetSorting(yourPartialAssetSortingMock).render(<YourTestComponent data-testid="yourTestId" />);
785
- * expect(screen.getByTestId("yourTestId")).toBeInTheDocument();
786
- * });
787
- * ...
788
- * @example
789
- * ...
790
- * it("should allow renderHook", async () => {
791
- * const { result } = await trackunitProviders().assetSorting(yourPartialAssetSortingMock).renderHook(() => useYourTestHook());
792
- * expect(result.current).toEqual(anything());
793
- * });
794
- * ...
795
- * @param assetSortingContext - Override the default context.
796
- * @returns { TrackunitProvidersMockBuilder } - The builder.
797
- */
798
- assetSorting(assetSortingContext) {
799
- this.selectedAssetSortingContext = { ...mockAssetSortingContext, ...assetSortingContext };
800
- return this;
801
- }
802
- /**
803
- * Use this to pass in a differerent export data context.
804
- * Defaults to mockExportDataContextState.
805
- *
806
- * This context is used by the useExportDataContext hook from lib "@trackunit/react-core-hooks"
807
- *
808
- * @see mockExportDataContextState
809
- * @example
810
- * ...
811
- * it("should allow render", async () => {
812
- * await trackunitProviders().exportData(yourPartialExportDataMock).render(<YourTestComponent data-testid="yourTestId" />);
813
- * expect(screen.getByTestId("yourTestId")).toBeInTheDocument();
814
- * });
815
- * ...
816
- */
817
- exportData(exportDataContext) {
818
- this.selectedExportDataContext = { ...mockExportDataContextState, ...exportDataContext };
819
- return this;
820
- }
821
- /**
822
- * Set OEM Branding context.
823
- * Defaults to mockOemBrandingContext.
824
- *
825
- * This context is used by the useAssetSorting hook from lib "@trackunit/react-core-hooks"
826
- *
827
- * @see mockOemBrandingContext
828
- * @example
829
- * ...
830
- * it("should allow render", async () => {
831
- * await trackunitProviders().oemBrandingContext(yourPartialOemBrandingMock).render(<YourTestComponent data-testid="yourTestId" />);
832
- * expect(screen.getByTestId("yourTestId")).toBeInTheDocument();
833
- * });
834
- * ...
835
- * @example
836
- * ...
837
- * it("should allow renderHook", async () => {
838
- * const { result } = await trackunitProviders().oemBrandingContext(yourPartialOemBrandingMock).renderHook(() => useYourTestHook());
839
- * expect(result.current).toEqual(anything());
840
- * });
841
- * ...
842
- * @param oemBrandingContext - Override the default context.
843
- */
844
- oemBrandingContext(oemBrandingContext) {
845
- this.selectedOemBrandingContext = { ...mockOemBrandingContext, ...oemBrandingContext };
846
- return this;
847
- }
848
- /**
849
- * Use this ToastContext with the given mocks.
850
- * Defaults to mockToastContext.
851
- *
852
- * This context is used by the useToast hook from lib "@trackunit/react-core-hooks"
853
- *
854
- * @see mockToastContext
855
- * @example
856
- * ...
857
- * it("should allow render", async () => {
858
- * await trackunitProviders().toast(yourPartialToastMock).render(<YourTestComponent data-testid="yourTestId" />);
859
- * expect(screen.getByTestId("yourTestId")).toBeInTheDocument();
860
- * });
861
- * ...
862
- * @example
863
- * ...
864
- * it("should allow renderHook", async () => {
865
- * const { result } = await trackunitProviders().toast(yourPartialToastMock).renderHook(() => useYourTestHook());
866
- * expect(result.current).toEqual(anything());
867
- * });
868
- * ...
869
- * @param toastContext - Override the default toast context.
870
- */
871
- toast(toastContext) {
872
- this.selectedToastContext = { ...mockToastContext, ...toastContext };
873
- return this;
874
- }
875
- /**
876
- * confirmationDialog
877
- */
878
- confirmationDialog(confirmationDialog) {
879
- this.selectedConfirmationDialogContext = { ...mockConfirmationDialogContext, ...confirmationDialog };
880
- return this;
881
- }
882
- /**
883
- * modalDialog
884
- */
885
- modalDialog(modalDialog) {
886
- this.selectedModalDialogContext = { ...mockModalDialogContext, ...modalDialog };
887
- return this;
888
- }
889
- /**
890
- * errorHandler
891
- */
892
- errorHandler(errorHandler) {
893
- this.selectedErrorHandler = { ...mockErrorHandlerContext, ...errorHandler };
894
- return this;
895
- }
896
- /**
897
- * Use this token.
898
- *
899
- * This context is used by the useToken hook from lib "@trackunit/react-core-hooks"
900
- *
901
- * @example
902
- * ...
903
- * it("should allow render", async () => {
904
- * await trackunitProviders().token(yourMockedToken).render(<YourTestComponent data-testid="yourTestId" />);
905
- * expect(screen.getByTestId("yourTestId")).toBeInTheDocument();
906
- * });
907
- * ...
908
- * @example
909
- * ...
910
- * it("should allow renderHook", async () => {
911
- * const { result } = await trackunitProviders().token(yourMockedToken).renderHook(() => useYourTestHook());
912
- * expect(result.current).toEqual(anything());
913
- * });
914
- * ...
915
- * @param token - The token to use.
916
- * @returns { TrackunitProvidersMockBuilder } - The builder.
917
- */
918
- token(token) {
919
- this.selectedTokenContext = { token };
920
- return this;
921
- }
922
- /**
923
- * Use this Router Props with the given mocks.
924
- *
925
- * This is used to provide a MemoryRouter from lib "@tanstack/react-router"
926
- *
927
- * @example
928
- * ...
929
- * it("should allow render", async () => {
930
- * await trackunitProviders().routerProps(yourRouterPropsMock).render(<YourTestComponent data-testid="yourTestId" />);
931
- * expect(screen.getByTestId("yourTestId")).toBeInTheDocument();
932
- * });
933
- * ...
934
- * @example
935
- * ...
936
- * it("should allow renderHook", async () => {
937
- * const { result } = await trackunitProviders().routerProps(yourRouterPropsMock).renderHook(() => useYourTestHook());
938
- * expect(result.current).toEqual(anything());
939
- * });
940
- * ...
941
- * @param routerProps - The router props to use.
942
- * @returns { TrackunitProvidersMockBuilder } - The builder.
943
- */
944
- routerProps(routerProps) {
945
- this.selectedRouterProps = routerProps;
946
- return this.rootRoute(routerProps.routeTree ? routerProps.routeTree : this.selectedRootRoute);
947
- }
948
- /**
949
- * Use this Manager Apollo Context Provider with the given mocks.
950
- *
951
- * This context is used by the useQuery and useLazyQuery hook from lib "@apollo/client"
952
- *
953
- * @see https://www.apollographql.com/docs/react/development-testing/testing
954
- * @example
955
- * ...
956
- * it("should allow render", async () => {
957
- * await trackunitProviders().apollo([yourApolloMocks]).render(<YourTestComponent data-testid="yourTestId" />);
958
- * expect(screen.getByTestId("yourTestId")).toBeInTheDocument();
959
- * });
960
- * ...
961
- * @example
962
- * ...
963
- * it("should allow renderHook", async () => {
964
- * const { result } = await trackunitProviders().apollo([yourApolloMocks]).renderHook(() => useYourTestHook());
965
- * expect(result.current).toEqual(anything());
966
- * });
967
- * ...
968
- * @param apolloMocks - The mocks to use for the ApolloProvider.
969
- */
970
- apollo(apolloMocks) {
971
- this.selectedApolloMocks = apolloMocks || [];
972
- return this;
973
- }
974
- /**
975
- * Validate the mocks that has been supplied to make sure they make sense.
976
- * Note: This function is overridden in builders extending this one.
977
- *
978
- * @returns {boolean} true or throws error if any invalid mocks
979
- */
980
- validateSuppliedMocks() {
981
- return true;
982
- }
983
- rootRoute(rootRoute) {
984
- this.selectedRootRoute = rootRoute;
985
- return this;
986
- }
987
- /**
988
- * Make sure this represent the same structure as the main index.tsx does.
989
- *
990
- * @param testChildren - the child element being tested.
991
- */
992
- getMockedCompositionRoot(testChildren) {
993
- return (jsxRuntime.jsx(reactCoreHooks.ErrorHandlingContextProvider, { value: this.selectedErrorHandler, children: jsxRuntime.jsx(reactCoreHooks.CurrentUserProvider, { value: this.selectedCurrentUserContext, children: jsxRuntime.jsx(reactCoreHooks.AnalyticsContext.Provider, { value: this.selectedAnalyticsContext, children: jsxRuntime.jsx(reactCoreHooks.UserSubscriptionProvider, { value: this.selectedUserSubscriptionContext, children: jsxRuntime.jsx(reactCoreHooks.OemBrandingContextProvider, { value: this.selectedOemBrandingContext, children: jsxRuntime.jsx(reactCoreHooks.TokenProvider, { value: this.selectedTokenContext, children: jsxRuntime.jsx(reactCoreHooks.ToastProvider, { value: this.selectedToastContext, children: jsxRuntime.jsx(reactCoreHooks.ConfirmationDialogProvider, { value: this.selectedConfirmationDialogContext, children: jsxRuntime.jsx(reactCoreHooks.FilterBarProvider, { value: this.selectedFilterBarValues, children: jsxRuntime.jsx(reactCoreHooks.ExportDataContext.Provider, { value: this.selectedExportDataContext, children: jsxRuntime.jsx(reactCoreHooks.AssetSortingProvider, { value: this.selectedAssetSortingContext, children: jsxRuntime.jsx(ApolloMockedProviderWithError, { addTypename: false, mocks: this.selectedApolloMocks, children: jsxRuntime.jsx(reactCoreHooks.NavigationContextProvider, { value: this.selectedNavigationContext, children: jsxRuntime.jsx(reactCoreHooks.CurrentUserPreferenceProvider, { value: this.selectedCurrentUserPreferenceContext, children: jsxRuntime.jsx(reactCoreHooks.EnvironmentContextProvider, { value: this.selectedEnvironmentContext, children: jsxRuntime.jsx(reactCoreHooks.ModalDialogContextProvider, { value: this.selectedModalDialogContext, children: jsxRuntime.jsx(reactCoreHooks.TimeRangeProvider, { value: this.selectedTimeRangeContext, children: jsxRuntime.jsx(reactCoreHooks.WidgetConfigProvider, { value: this.selectedWidgetConfigContext, children: testChildren }) }) }) }) }) }) }) }) }) }) }) }) }) }) }) }) }) }));
994
- }
995
- getMockedCompositionRootWithRouter(testChildren) {
996
- const childrenWithRouter = (jsxRuntime.jsx(RouterContainer, { addTestRootContainer: true, rootRoute: this.selectedRootRoute, selectedRouterProps: this.selectedRouterProps, children: testChildren }));
997
- return this.getMockedCompositionRoot(childrenWithRouter);
998
- }
999
- /**
1000
- * This will return the mocked composition root.
1001
- */
1002
- async renderHook(callback, parentElement) {
1003
- this.validateSuppliedMocks();
1004
- // This ensures correct act loading when using hooks and not loaded if this build is used for storybook
1005
- const hookRenderer = await Promise.resolve().then(function () { return require('./HookRenderer.cjs.js'); });
1006
- let rerenderCounter = 0;
1007
- const renderedHook = await hookRenderer.reactHooksRenderHook(callback, children => this.getMockedCompositionRoot(jsxRuntime.jsx(RerenderProvider, { counter: rerenderCounter, children: jsxRuntime.jsx(RouterContainer, { addTestRootContainer: true, rootRoute: this.selectedRootRoute, selectedRouterProps: this.selectedRouterProps, children: jsxRuntime.jsx(RerenderComponent, { children: parentElement ? parentElement(children) : children }) }) })));
1008
- return {
1009
- ...renderedHook,
1010
- rerender: async (props) => {
1011
- rerenderCounter += 1;
1012
- renderedHook.rerender(props);
1013
- },
1014
- };
1015
- }
1016
- /**
1017
- * This will use react-testing-library.render the child in the correct mocked hierarchy of context providers.
1018
- *
1019
- * @see https://testing-library.com/docs/react-testing-library/api#render
1020
- * @param child - the child element being tested.
1021
- */
1022
- async render(child) {
1023
- this.validateSuppliedMocks();
1024
- let mountedcomponent;
1025
- await react$1.act(async () => {
1026
- mountedcomponent = react$1.render(child, {
1027
- wrapper: ({ children }) => this.getMockedCompositionRootWithRouter(children),
1028
- });
1029
- await flushPromises();
1030
- });
1031
- await react$1.act(async () => {
1032
- await flushPromises();
1033
- });
1034
- await react$1.act(async () => {
1035
- await flushPromises();
1036
- });
1037
- return mountedcomponent;
1038
- }
1039
- /**
1040
- * Test that a hook can handle rerenders with the same props and returns a stable result.
1041
- * This is useful for testing that hooks properly memoize their results.
1042
- * Returns true if the hook result is referentially stable after rerender.
1043
- * Uses Object.is() for comparison to match Jest's toBe() behavior exactly.
1044
- *
1045
- * **Requirements:**
1046
- * - The hook must return a non-null, non-undefined value
1047
- * - If the hook returns null or undefined, the test will throw an error
1048
- * - This ensures the test is actually verifying stability of a meaningful result
1049
- *
1050
- * @example
1051
- * ```ts
1052
- * expect(await trackunitProviders().verifyHookStability(() =>
1053
- * useAssetMetadataChartData({
1054
- * filters: {},
1055
- * selectedChartOption: "metadataCompleteness",
1056
- * })
1057
- * )).toBe(true);
1058
- * ```
1059
- * @param callback - The hook to test
1060
- * @param parentElement - Optional parent element wrapper
1061
- * @throws Error if the hook result is undefined or null (to ensure meaningful stability testing)
1062
- * @returns {boolean} true if the result is referentially stable after rerender (using Object.is()), false otherwise
1063
- */
1064
- async verifyHookStability(callback, parentElement) {
1065
- const { result, rerender } = await this.renderHook(callback, parentElement);
1066
- // Wait for effects to settle after initial render
1067
- await flushPromisesInAct();
1068
- const initial = result.current;
1069
- await rerender();
1070
- // Wait for effects to settle after rerender
1071
- await flushPromisesInAct();
1072
- const updated = result.current;
1073
- if (updated === undefined || updated === null) {
1074
- throw new Error("Updated result is undefined or null, so the test is not testing anything");
1075
- }
1076
- return Object.is(updated, initial);
1077
- }
1078
- /**
1079
- * This will return the children in the correct mocked hierarchy of context providers.
1080
- */
1081
- storybook(child) {
1082
- return this.getMockedCompositionRoot(child);
1083
- }
1084
- }
1085
- /**
1086
- * This is the default mock builder for the TrackunitProviders.
1087
- */
1088
- const trackunitProviders = () => new TrackunitProvidersMockBuilder();
1089
-
1090
- /**
1091
- * Differentiate between the first and subsequent renders.
1092
- *
1093
- * @returns {boolean} Returns true if it is the first render, false otherwise.
1094
- */
1095
- const useIsFirstRender = () => {
1096
- const [isFirstRender, setIsFirstRender] = React.useState(true);
1097
- React.useEffect(() => {
1098
- setIsFirstRender(false);
1099
- }, []);
1100
- return isFirstRender;
1101
- };
1102
-
1103
- /**
1104
- * Logs props that have changed.
1105
- * Use this for debugging which props force a component to re-render.
1106
- * This is a hook version of the class component lifecycle method `componentDidUpdate`.
1107
- * ALWAYS wrap in your own object.
1108
- *
1109
- * @param id optional id to use for logging or it will guess the id from the stack trace
1110
- * @param propsToWatch all the props to watch for changes
1111
- * @param dontLogReRender if true, will not log the re-render message nice if you have a lot of re-renders
1112
- * @example
1113
- * const propsToWatch = { foo: props.foo, bar: props.bar };
1114
- * useDebugger(propsToWatch);
1115
- */
1116
- const useDebugger = (propsToWatch, id, dontLogReRender) => {
1117
- const prevPropsRef = React.useRef(propsToWatch);
1118
- const uniqueId = React.useMemo(() => {
1119
- let stackId = id || (propsToWatch && propsToWatch.id);
1120
- const stack = new Error().stack;
1121
- if (!stackId && stack) {
1122
- const stackLines = stack.split("\n");
1123
- for (let i = 0; i < stackLines.length; i++) {
1124
- const stackLine = stackLines[i];
1125
- if (stackLine?.includes("useDebugger")) {
1126
- stackId = stackLines[i + 1]?.trim().split(" ")[1];
1127
- break;
1128
- }
1129
- }
1130
- }
1131
- return stackId || "unknown-id";
1132
- }, [id, propsToWatch]);
1133
- const isFirstRender = useIsFirstRender();
1134
- if (isFirstRender) {
1135
- // eslint-disable-next-line no-console
1136
- console.log("First-render", uniqueId, window.location.pathname);
1137
- }
1138
- else if (dontLogReRender !== true) {
1139
- // eslint-disable-next-line no-console
1140
- console.log("Re-render", uniqueId, window.location.pathname);
1141
- }
1142
- React.useEffect(() => {
1143
- const changedProps = Object.entries(propsToWatch || {}).reduce((result, [key, value]) => {
1144
- if (prevPropsRef.current && prevPropsRef.current[key] !== value) {
1145
- result[key + ""] = [prevPropsRef.current[key], value];
1146
- }
1147
- return result;
1148
- }, {});
1149
- if (sharedUtils.objectKeys(changedProps).length > 0) {
1150
- sharedUtils.objectKeys(changedProps).forEach(changedProp => {
1151
- // eslint-disable-next-line no-console
1152
- console.log(`${uniqueId} changed property: ${changedProp}`);
1153
- // JSON stringify is used to avoid console.table from logging the object reference
1154
- const result = JSON.parse(safeStringify(changedProps[changedProp]));
1155
- const result0 = result[0];
1156
- const result1 = result[1];
1157
- result0 &&
1158
- typeof result0 === "object" &&
1159
- sharedUtils.objectKeys(result0).forEach(prop => {
1160
- result0[prop] = typeof result0[prop] === "object" ? JSON.stringify(result0[prop]) : result0[prop];
1161
- });
1162
- result1 &&
1163
- typeof result1 === "object" &&
1164
- sharedUtils.objectKeys(result1).forEach(prop => {
1165
- result1[prop] = typeof result1[prop] === "object" ? JSON.stringify(result1[prop]) : result1[prop];
1166
- });
1167
- // eslint-disable-next-line no-console
1168
- console.table([result0, result1]);
1169
- });
1170
- // eslint-disable-next-line no-console
1171
- console.dir(changedProps);
1172
- }
1173
- prevPropsRef.current = propsToWatch;
1174
- }, [propsToWatch, uniqueId]);
1175
- };
1176
- /**
1177
- * Debugger component for debugging state changes and re-renders.
1178
- *
1179
- * This component will log when it is mounted, re-renders or unmounted.
1180
- * It will also log when any of its props change.
1181
- *
1182
- * @param id optional id to use for logging
1183
- * @param stop if true, will stop execution and open debugger
1184
- * @param logPropsChanges optional object with props to watch for changes
1185
- * @param children the children to render
1186
- */
1187
- const Debugger = ({ id, logPropsChanges, stop, children, }) => {
1188
- const uniqueId = id ||
1189
- // @ts-ignore
1190
- React["__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED"]?.ReactCurrentOwner?.current?._debugOwner?.type?.name ||
1191
- new Error().stack?.split("\n")[2]?.trim() ||
1192
- "unknown-id";
1193
- useDebugger(logPropsChanges || {}, id);
1194
- const uniqueIdRef = React.useRef(uniqueId);
1195
- React.useEffect(() => {
1196
- const currentUniqueId = uniqueIdRef.current;
1197
- // eslint-disable-next-line no-console
1198
- console.log(`${currentUniqueId} Debugger is mounting`);
1199
- return () => {
1200
- // eslint-disable-next-line no-console
1201
- console.log(`${currentUniqueId} Debugger is unmounting`);
1202
- };
1203
- }, []);
1204
- if (stop === true) {
1205
- // eslint-disable-next-line no-debugger
1206
- debugger;
1207
- }
1208
- return jsxRuntime.jsx("div", { className: "Debugger", children: children });
1209
- };
1210
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1211
- const safeStringify = (obj) => {
1212
- const seen = new WeakSet();
1213
- return JSON.stringify(obj, function (key, value) {
1214
- if (typeof value === "object" && value !== null) {
1215
- if (seen.has(value)) {
1216
- return undefined; // Omit circular reference
1217
- }
1218
- seen.add(value);
1219
- }
1220
- return value;
1221
- });
1222
- };
1223
-
1224
- /**
1225
- *
1226
- * @param document Document that represents the specific GQL query / mutation schema.
1227
- * @param variables Variables that should be passed to the query / mutation.
1228
- * Note that an *exact* match between the mock and operation is necessary.
1229
- * @param data Data object to be returned.
1230
- * Note that *all* properties should be given a value, use `null` in place of `undefined`,
1231
- * otherwise nothing will be returned.
1232
- * @param error ApolloError object to be returned.
1233
- * @returns {MockedResponse} with data attached, this response can be passed to the mocked ApolloProvider.
1234
- * @see [Testing React components using MockedProvider and associated APIs](https://www.apollographql.com/docs/react/development-testing/testing/)
1235
- * @example
1236
- * it("should show the brand fetched from graphql", async () => {
1237
- * const mock = queryFor(GetDemoAssetDocument, {
1238
- * assetId: "assetId",
1239
- * });
1240
- *
1241
- * AssetRuntime.getAssetInfo = jest.fn().mockResolvedValue({ assetId: "assetId" });
1242
- * await trackunitProviders()
1243
- * .apollo([mock])
1244
- * .render(<App />);
1245
- *
1246
- * # mock.data is the combined result of what is passed in from queryFor and what is generated by generateMockData
1247
- * expect(screen.getByText(`Brand: ${mock.data.asset?.brand}`)).toBeInTheDocument();
1248
- * });
1249
- */
1250
- const queryFor = (document, variables, data, error, maxUsageCount = 1) => {
1251
- return {
1252
- request: {
1253
- query: document,
1254
- variables,
1255
- },
1256
- data,
1257
- maxUsageCount,
1258
- newData: () => {
1259
- if (process.env.VSCODE_INSPECTOR_OPTIONS || process.env.DEBUG) {
1260
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1261
- const name = document.definitions[0].name.value;
1262
- // eslint-disable-next-line no-console
1263
- console.log("Found Response for: " +
1264
- name +
1265
- " for variables: " +
1266
- JSON.stringify(variables, null, 2) +
1267
- " Returning: " +
1268
- "{ data: " +
1269
- JSON.stringify(data, null, 2) +
1270
- ", error: " +
1271
- JSON.stringify(error, null, 2) +
1272
- "}");
1273
- }
1274
- return {
1275
- data,
1276
- errors: error ? [new graphql.GraphQLError(error.message)] : undefined,
1277
- };
1278
- },
1279
- };
1280
- };
1281
- /**
1282
- *
1283
- * @param document Document that represents the specific GQL query / mutation schema.
1284
- * @param variables Variables that should be passed to the query / mutation.
1285
- * Note that an *exact* match between the mock and operation is necessary.
1286
- * @param data Data object to be returned.
1287
- * Note that *all* properties should be given a value, use `null` in place of `undefined`,
1288
- * otherwise nothing will be returned.
1289
- * @param error ApolloError object to be returned.
1290
- * @returns {MockedResponse} that can be passed to the mocked ApolloProvider.
1291
- * @see [Testing React components using MockedProvider and associated APIs](https://www.apollographql.com/docs/react/development-testing/testing/)
1292
- */
1293
- const queryForHook = (hookFn, document, variables, data, error) => {
1294
- return {
1295
- request: {
1296
- query: document,
1297
- variables,
1298
- },
1299
- newData: () => {
1300
- if (process.env.VSCODE_INSPECTOR_OPTIONS || process.env.DEBUG) {
1301
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1302
- const name = document.definitions[0].name.value;
1303
- // eslint-disable-next-line no-console
1304
- console.log("Found Response for: " +
1305
- name +
1306
- " for variables: " +
1307
- JSON.stringify(variables, null, 2) +
1308
- " Returning: " +
1309
- "{ data: " +
1310
- JSON.stringify(data, null, 2) +
1311
- ", error: " +
1312
- JSON.stringify(error, null, 2) +
1313
- "}");
1314
- }
1315
- return {
1316
- data,
1317
- errors: error ? [new graphql.GraphQLError(error.message)] : undefined,
1318
- };
1319
- },
1320
- };
1321
- };
1322
-
1323
- /**
1324
- * This helps validate the IrisApp is exposed correctly it must expose:
1325
- * - bootstrap
1326
- * - mount
1327
- * - unmount
1328
- * According to the single spa spec.
1329
- *
1330
- * Your test could look like this
1331
- *
1332
- * @example
1333
- * import * as IrisApp from "./index";
1334
- describe("App", () => {
1335
- it("Should validate", async () => {
1336
- const result = await validateIrisApp(IrisApp);
1337
- expect(result).toBeNull();
1338
- });
1339
- });
1340
- * @param irisApp Import the index ts(x) file as above and pass it in.
1341
- * @returns {null|string} if everything is good - otherwise a string telling you what is wrong.
1342
- */
1343
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1344
- const validateIrisApp = async (irisApp) => {
1345
- if (!irisApp.bootstrap || typeof irisApp.bootstrap !== "function") {
1346
- return "Missing a bootstrap function";
1347
- }
1348
- if (!irisApp.mount || typeof irisApp.mount !== "function") {
1349
- return "Missing a mount function";
1350
- }
1351
- if (!irisApp.unmount || typeof irisApp.unmount !== "function") {
1352
- return "Missing an unmount function";
1353
- }
1354
- if (irisApp.update && typeof irisApp.update !== "function") {
1355
- return "Update must be a function";
1356
- }
1357
- return null;
1358
- };
1359
-
1360
- exports.Debugger = Debugger;
1361
- exports.TrackunitProvidersMockBuilder = TrackunitProvidersMockBuilder;
1362
- exports.doNothing = doNothing;
1363
- exports.flushPromises = flushPromises;
1364
- exports.flushPromisesInAct = flushPromisesInAct;
1365
- exports.mockAnalyticsContext = mockAnalyticsContext;
1366
- exports.mockAssetSortingContext = mockAssetSortingContext;
1367
- exports.mockCurrentUserContext = mockCurrentUserContext;
1368
- exports.mockEnvironmentContext = mockEnvironmentContext;
1369
- exports.mockFilterBarContext = mockFilterBarContext;
1370
- exports.mockOemBrandingContext = mockOemBrandingContext;
1371
- exports.mockToastContext = mockToastContext;
1372
- exports.mockUserSubscriptionContext = mockUserSubscriptionContext;
1373
- exports.queryFor = queryFor;
1374
- exports.queryForHook = queryForHook;
1375
- exports.trackunitProviders = trackunitProviders;
1376
- exports.useDebugger = useDebugger;
1377
- exports.validateIrisApp = validateIrisApp;
3
+ var index = require('./index.cjs2.js');
4
+ require('@trackunit/iris-app-runtime-core-api');
5
+ require('react/jsx-runtime');
6
+ require('react');
7
+ require('react-dom/test-utils');
8
+ require('react-dom');
9
+ require('react-dom/client');
10
+ require('@trackunit/react-core-hooks');
11
+ require('es-toolkit');
12
+ require('@apollo/client');
13
+ require('@apollo/client/dev');
14
+ require('@apollo/client/link/error');
15
+ require('@apollo/client/testing');
16
+ require('@trackunit/shared-utils');
17
+ require('@apollo/client/react');
18
+ require('@tanstack/react-router');
19
+ require('graphql');
20
+
21
+
22
+
23
+ exports.Debugger = index.Debugger;
24
+ exports.TrackunitProvidersMockBuilder = index.TrackunitProvidersMockBuilder;
25
+ exports.doNothing = index.doNothing;
26
+ exports.flushPromises = index.flushPromises;
27
+ exports.flushPromisesInAct = index.flushPromisesInAct;
28
+ exports.mockAnalyticsContext = index.mockAnalyticsContext;
29
+ exports.mockAssetSortingContext = index.mockAssetSortingContext;
30
+ exports.mockCurrentUserContext = index.mockCurrentUserContext;
31
+ exports.mockEnvironmentContext = index.mockEnvironmentContext;
32
+ exports.mockFilterBarContext = index.mockFilterBarContext;
33
+ exports.mockOemBrandingContext = index.mockOemBrandingContext;
34
+ exports.mockToastContext = index.mockToastContext;
35
+ exports.mockUserSubscriptionContext = index.mockUserSubscriptionContext;
36
+ exports.queryFor = index.queryFor;
37
+ exports.queryForHook = index.queryForHook;
38
+ exports.trackunitProviders = index.trackunitProviders;
39
+ exports.useDebugger = index.useDebugger;
40
+ exports.validateIrisApp = index.validateIrisApp;