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