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