@trackunit/react-core-contexts-test 0.1.243 → 0.1.246

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