@trackunit/react-core-contexts-test 0.1.34 → 0.1.35-alpha-0b53b6cf53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,34 @@
1
+ 'use strict';
2
+
3
+ var index = require('./index2.cjs');
4
+ var jsxRuntime = require('react/jsx-runtime');
5
+ var react = require('@testing-library/react');
6
+ var pure = require('@testing-library/react/pure');
7
+ require('@trackunit/react-core-contexts-api');
8
+ require('@trackunit/react-core-hooks');
9
+ require('@trackunit/tailwind-styled-components');
10
+ require('react-router-dom');
11
+ require('@apollo/client');
12
+ require('@apollo/client/link/error');
13
+ require('@apollo/client/testing');
14
+ require('graphql');
15
+
16
+ const reactHooksRenderHook = (callback, getMockedCompositionRoot) => index.__awaiter(void 0, void 0, void 0, function* () {
17
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
18
+ const wrapper = ({ children }) => {
19
+ // eslint-disable-next-line react/jsx-no-useless-fragment
20
+ return getMockedCompositionRoot(jsxRuntime.jsx(jsxRuntime.Fragment, { children: children }));
21
+ };
22
+ let renderedHook;
23
+ // This is added here to make storybook work and to ensure the right act is loaded for hooks.
24
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
25
+ yield react.act(() => index.__awaiter(void 0, void 0, void 0, function* () {
26
+ renderedHook = yield pure.renderHook(callback, { wrapper });
27
+ }));
28
+ yield react.act(() => index.__awaiter(void 0, void 0, void 0, function* () {
29
+ yield index.flushPromises();
30
+ }));
31
+ return renderedHook;
32
+ });
33
+
34
+ exports.reactHooksRenderHook = reactHooksRenderHook;
package/index.cjs ADDED
@@ -0,0 +1,27 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var index = require('./index2.cjs');
6
+ require('react/jsx-runtime');
7
+ require('@testing-library/react');
8
+ require('@trackunit/react-core-contexts-api');
9
+ require('@trackunit/react-core-hooks');
10
+ require('@trackunit/tailwind-styled-components');
11
+ require('react-router-dom');
12
+ require('@apollo/client');
13
+ require('@apollo/client/link/error');
14
+ require('@apollo/client/testing');
15
+ require('graphql');
16
+
17
+
18
+
19
+ exports.MockContextProviderBuilder = index.MockContextProviderBuilder;
20
+ exports.doNothing = index.doNothing;
21
+ exports.flushPromises = index.flushPromises;
22
+ exports.flushPromisesInAct = index.flushPromisesInAct;
23
+ exports.mockCurrentUserContext = index.mockCurrentUserContext;
24
+ exports.mockEnvironmentContext = index.mockEnvironmentContext;
25
+ exports.queryFor = index.queryFor;
26
+ exports.rootContext = index.rootContext;
27
+ exports.validateIrisApp = index.validateIrisApp;
package/index2.cjs ADDED
@@ -0,0 +1,420 @@
1
+ 'use strict';
2
+
3
+ var jsxRuntime = require('react/jsx-runtime');
4
+ var react = require('@testing-library/react');
5
+ var reactCoreContextsApi = require('@trackunit/react-core-contexts-api');
6
+ var reactCoreHooks = require('@trackunit/react-core-hooks');
7
+ var tailwindStyledComponents = require('@trackunit/tailwind-styled-components');
8
+ var reactRouterDom = require('react-router-dom');
9
+ var client = require('@apollo/client');
10
+ var error = require('@apollo/client/link/error');
11
+ var testing = require('@apollo/client/testing');
12
+ var graphql = require('graphql');
13
+
14
+ /******************************************************************************
15
+ Copyright (c) Microsoft Corporation.
16
+
17
+ Permission to use, copy, modify, and/or distribute this software for any
18
+ purpose with or without fee is hereby granted.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
21
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
22
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
23
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
24
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
25
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
26
+ PERFORMANCE OF THIS SOFTWARE.
27
+ ***************************************************************************** */
28
+
29
+ function __rest(s, e) {
30
+ var t = {};
31
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
32
+ t[p] = s[p];
33
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
34
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
35
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
36
+ t[p[i]] = s[p[i]];
37
+ }
38
+ return t;
39
+ }
40
+
41
+ function __awaiter(thisArg, _arguments, P, generator) {
42
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
43
+ return new (P || (P = Promise))(function (resolve, reject) {
44
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
45
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
46
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
47
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
48
+ });
49
+ }
50
+
51
+ const defaultOptions = {
52
+ mutate: {
53
+ errorPolicy: "all",
54
+ },
55
+ query: {
56
+ errorPolicy: "all",
57
+ },
58
+ };
59
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
60
+ function ApolloMockedProviderWithError(props) {
61
+ const { mocks } = props, otherProps = __rest(props, ["mocks"]);
62
+ const mockLink = new testing.MockLink(mocks);
63
+ const errorLoggingLink = error.onError(({ graphQLErrors, networkError }) => {
64
+ if (graphQLErrors) {
65
+ // eslint-disable-next-line array-callback-return
66
+ graphQLErrors.map(({ message, locations, path }) => {
67
+ if (process.env["VSCODE_INSPECTOR_OPTIONS"] || process.env["DEBUG"]) {
68
+ // eslint-disable-next-line no-console
69
+ console.log(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`);
70
+ }
71
+ });
72
+ }
73
+ if (networkError) {
74
+ if (process.env["VSCODE_INSPECTOR_OPTIONS"] || process.env["DEBUG"]) {
75
+ // eslint-disable-next-line no-console
76
+ console.log(`[Network error]: ${networkError}`);
77
+ }
78
+ }
79
+ });
80
+ const link = client.ApolloLink.from([errorLoggingLink, mockLink]);
81
+ return (jsxRuntime.jsx(testing.MockedProvider, Object.assign({}, otherProps, { link: link, defaultOptions: Object.assign(Object.assign({}, defaultOptions), { watchQuery: { fetchPolicy: "no-cache" } }) })));
82
+ }
83
+
84
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
85
+ const doNothing = () => {
86
+ /* Do nothing */
87
+ };
88
+
89
+ const mockAssetSortingContext = {
90
+ setSortBy: doNothing,
91
+ sortingState: {
92
+ sortBy: reactCoreContextsApi.AssetSortByProperty.Criticality,
93
+ order: reactCoreContextsApi.SortOrder.Desc,
94
+ },
95
+ };
96
+
97
+ const mockCurrentUserContext = (overrides = {}) => (Object.assign({ userName: "", userRole: "", customerId: 12345, userId: 154312, tasUserId: "751ea227-f199-4d00-925f-a608312c5e45", email: "", name: "", accountId: "", assumedUser: null, jobTitle: "", isAuthenticated: true, isVerified: true, isAccountOwner: true }, overrides));
98
+
99
+ const mockEnvironmentContext = {
100
+ auth: {
101
+ url: "",
102
+ clientId: "",
103
+ issuer: "",
104
+ },
105
+ managerClassicUrl: "https://sso.trackunit.com",
106
+ googleMapsApiKey: "",
107
+ amplitudeApiKey: "",
108
+ graphqlLegacyUrl: "",
109
+ graphqlPublicUrl: "",
110
+ graphqlManagerUrl: "",
111
+ graphqlManagerImageUploadUrl: "",
112
+ graphqlReportUrl: "",
113
+ buildVersion: "",
114
+ commitNumber: 0,
115
+ buildDate: "",
116
+ irisAppSdkServerUrl: "",
117
+ publicUrl: "",
118
+ isDev: true,
119
+ environment: "",
120
+ sentryDsn: "",
121
+ sessionId: "",
122
+ tracingHeaders: {
123
+ "X-TrackunitAppVersion": "",
124
+ "session-id": "",
125
+ },
126
+ trackunitRestApiUrl: "",
127
+ };
128
+
129
+ const mockUserSubscriptionProviderValue = (features, packageType) => {
130
+ return {
131
+ numberOfDaysWithAccessToHistoricalData: 30,
132
+ numberOfDaysWithAccessToHistoricalInsights: 30,
133
+ features,
134
+ packageType,
135
+ };
136
+ };
137
+
138
+ const flushPromises = (waitTimeInMS = 0) => {
139
+ return new Promise(resolve => {
140
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
141
+ if (global.ORG_setTimeout) {
142
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
143
+ return global.ORG_setTimeout(() => global.ORG_setTimeout(resolve, waitTimeInMS), 1);
144
+ }
145
+ else {
146
+ setTimeout(() => setTimeout(resolve, waitTimeInMS), 1);
147
+ }
148
+ });
149
+ };
150
+ const flushPromisesInAct = (waitTimeInMS = 0) => {
151
+ return react.act(() => {
152
+ return new Promise(resolve => {
153
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
154
+ if (global.ORG_setTimeout) {
155
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
156
+ return global.ORG_setTimeout(() => global.ORG_setTimeout(resolve, waitTimeInMS), 1);
157
+ }
158
+ else {
159
+ setTimeout(() => setTimeout(resolve, waitTimeInMS), 1);
160
+ }
161
+ });
162
+ });
163
+ };
164
+
165
+ /**
166
+ * This builder allows you to enable providers using the builder pattern, and then call 1 of either:
167
+ * - render
168
+ * - mount
169
+ */
170
+ class MockContextProviderBuilder {
171
+ constructor() {
172
+ this.selectedEnvironmentContext = mockEnvironmentContext;
173
+ this.selectedTokenContext = { token: "fakeToken" };
174
+ this.userSubscriptionPackageType = reactCoreContextsApi.UserSubscriptionPackage.INSIGHT;
175
+ this.features = [];
176
+ this.selectedApolloMocks = [];
177
+ this.selectedRouterProps = {};
178
+ this.selectedAssumedUser = mockCurrentUserContext().assumedUser;
179
+ this.selectedGlobalSelection = { selection: null };
180
+ this.selectedAssetSortingContext = mockAssetSortingContext;
181
+ }
182
+ /**
183
+ * Use this Environment Context.
184
+ *
185
+ * @param environmentContext
186
+ */
187
+ environment(environmentContext) {
188
+ this.selectedEnvironmentContext = environmentContext || mockEnvironmentContext;
189
+ return this;
190
+ }
191
+ /**
192
+ * Use this token.
193
+ *
194
+ * @param token
195
+ */
196
+ token(token) {
197
+ this.selectedTokenContext = { token };
198
+ return this;
199
+ }
200
+ /**
201
+ * Use this to pass in userSubscriptionPackage.
202
+ *
203
+ * @param developerSettingsContext
204
+ */
205
+ userSubscriptionPackage(userSubscriptionPackage) {
206
+ if (userSubscriptionPackage) {
207
+ this.userSubscriptionPackageType = userSubscriptionPackage;
208
+ }
209
+ return this;
210
+ }
211
+ /**
212
+ * Use this to pass in SupportedFeatures.
213
+ *
214
+ * @param developerSettingsContext
215
+ */
216
+ supportedFeatures(features) {
217
+ if (features) {
218
+ this.features = features.map(feature => {
219
+ return {
220
+ id: feature,
221
+ name: feature,
222
+ };
223
+ });
224
+ }
225
+ return this;
226
+ }
227
+ /**
228
+ * Assume this user
229
+ *
230
+ * @param assumeUser
231
+ */
232
+ assumeUser(assumeUser) {
233
+ this.selectedAssumedUser = assumeUser;
234
+ return this;
235
+ }
236
+ /**
237
+ * Use this Router Props with the given mocks.
238
+ *
239
+ * @param routerProps
240
+ */
241
+ routerProps(routerProps) {
242
+ this.selectedRouterProps = routerProps || {};
243
+ return this;
244
+ }
245
+ /**
246
+ * Use this global selection.
247
+ *
248
+ * @param globalSelection
249
+ */
250
+ globalSelection(globalSelection) {
251
+ this.selectedGlobalSelection = { selection: globalSelection };
252
+ return this;
253
+ }
254
+ /**
255
+ * Set global asset sorting context.
256
+ *
257
+ * @param overrides - Override the default context.
258
+ */
259
+ assetSorting(overrides) {
260
+ this.selectedAssetSortingContext = Object.assign(Object.assign({}, mockAssetSortingContext), overrides);
261
+ return this;
262
+ }
263
+ renderHook(callback, parentElement) {
264
+ return __awaiter(this, void 0, void 0, function* () {
265
+ this.validateSuppliedMocks();
266
+ // This ensures correct act loading when using hooks
267
+ const hookRenderer = yield Promise.resolve().then(function () { return require('./HookRenderer.cjs'); });
268
+ return hookRenderer.reactHooksRenderHook(callback, children => this.getMockedCompositionRoot(parentElement ? parentElement(children) : children));
269
+ });
270
+ }
271
+ /**
272
+ * Use this Manager Apollo Context Provider with the given mocks.
273
+ *
274
+ * @param apolloMocks
275
+ */
276
+ apollo(apolloMocks) {
277
+ this.selectedApolloMocks = apolloMocks || [];
278
+ return this;
279
+ }
280
+ /**
281
+ * This will use RTL.render the child in the correct mocked hierarchy of context providers.
282
+ *
283
+ * @param child - the child element being tested.
284
+ */
285
+ render(child) {
286
+ return __awaiter(this, void 0, void 0, function* () {
287
+ this.validateSuppliedMocks();
288
+ let mountedcomponent;
289
+ yield react.act(() => __awaiter(this, void 0, void 0, function* () {
290
+ mountedcomponent = react.render(child, {
291
+ wrapper: ({ children }) => this.getMockedCompositionRoot(children),
292
+ });
293
+ yield flushPromises();
294
+ }));
295
+ yield react.act(() => __awaiter(this, void 0, void 0, function* () {
296
+ yield flushPromises();
297
+ }));
298
+ yield react.act(() => __awaiter(this, void 0, void 0, function* () {
299
+ yield flushPromises();
300
+ }));
301
+ return mountedcomponent;
302
+ });
303
+ }
304
+ /**
305
+ * Validate the mocks that has been supplied to make sure they make sense.
306
+ * Note: This function is overriden in builders extending this one.
307
+ *
308
+ * @returns true or throws error if any invalid mocks
309
+ */
310
+ validateSuppliedMocks() {
311
+ return true;
312
+ }
313
+ /**
314
+ * Make sure this represent the same structure as the main index.tsx does.
315
+ *
316
+ * @param testChildren - the child element being tested.
317
+ * @param addTestRootContainer - if you want to add a root container to the test.
318
+ */
319
+ getMockedCompositionRoot(testChildren, addTestRootContainer = true) {
320
+ return (jsxRuntime.jsx(reactCoreHooks.EnvironmentContextProvider, Object.assign({ value: this.selectedEnvironmentContext }, { children: jsxRuntime.jsx(reactRouterDom.MemoryRouter, Object.assign({}, this.selectedRouterProps, { children: jsxRuntime.jsx(reactCoreHooks.CurrentUserProvider, Object.assign({ value: mockCurrentUserContext({ assumedUser: this.selectedAssumedUser }) }, { children: jsxRuntime.jsx(reactCoreHooks.UserSubscriptionProvider, Object.assign({ value: mockUserSubscriptionProviderValue(this.features, this.userSubscriptionPackageType) }, { children: jsxRuntime.jsx(reactCoreHooks.TokenProvider, Object.assign({ value: this.selectedTokenContext }, { children: jsxRuntime.jsx(reactCoreHooks.ToastProvider, Object.assign({ value: { addToast: () => __awaiter(this, void 0, void 0, function* () { }) } }, { children: jsxRuntime.jsx(reactCoreHooks.GlobalSelectionProvider, Object.assign({ value: this.selectedGlobalSelection }, { children: jsxRuntime.jsx(reactCoreHooks.AssetSortingProvider, Object.assign({ value: this.selectedAssetSortingContext }, { children: jsxRuntime.jsx(ApolloMockedProviderWithError, Object.assign({ mocks: this.selectedApolloMocks, addTypename: false }, { children: addTestRootContainer ? (jsxRuntime.jsx(TestRoot, Object.assign({ "data-testid": "testRoot" }, { children: testChildren }))) : (jsxRuntime.jsx("div", { children: testChildren })) })) })) })) })) })) })) })) })) })));
321
+ }
322
+ }
323
+ const rootContext = () => new MockContextProviderBuilder();
324
+ const TestRoot = tailwindStyledComponents.tw.div `
325
+ --tw-scale-x: 0.99;
326
+ --tw-scale-y: 0.99;
327
+ w[1024px];
328
+ h[1000px];
329
+ inline-block;
330
+ `;
331
+
332
+ /**
333
+ *
334
+ * @param document Document that represents the specific GQL query / mutation schema.
335
+ * @param variables Variables that should be passed to the query / mutation.
336
+ * Note that an *exact* match between the mock and operation is necessary.
337
+ * @param data Data object to be returned.
338
+ * Note that *all* properties should be given a value, use `null` in place of `undefined`,
339
+ * otherwise nothing will be returned.
340
+ * @param error ApolloError object to be returned.
341
+ * @returns MockedResponse that can be passed to the mocked ApolloProvider.
342
+ * @see [Testing React components using MockedProvider and associated APIs](https://www.apollographql.com/docs/react/development-testing/testing/)
343
+ */
344
+ const queryFor = (document, variables, data, error) => {
345
+ return {
346
+ request: {
347
+ query: document,
348
+ variables,
349
+ },
350
+ newData: () => {
351
+ if (process.env["VSCODE_INSPECTOR_OPTIONS"] || process.env["DEBUG"]) {
352
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
353
+ const name = document.definitions[0].name.value;
354
+ // eslint-disable-next-line no-console
355
+ console.log("Found Response for: " +
356
+ name +
357
+ " for variables: " +
358
+ JSON.stringify(variables, null, 2) +
359
+ " Returning: " +
360
+ "{ data: " +
361
+ JSON.stringify(data, null, 2) +
362
+ ", error: " +
363
+ JSON.stringify(error, null, 2) +
364
+ "}");
365
+ }
366
+ return {
367
+ data,
368
+ errors: error ? [new graphql.GraphQLError(error.message)] : undefined,
369
+ };
370
+ },
371
+ };
372
+ };
373
+
374
+ /**
375
+ * This helps validate the IrisApp is exposed correctly it must expose:
376
+ * - bootstrap
377
+ * - mount
378
+ * - unmount
379
+ * According to the single spa spec.
380
+ *
381
+ * Your test could look like this
382
+ * @example
383
+ * import * as IrisApp from "./index";
384
+ describe("App", () => {
385
+ it("Should validate", async () => {
386
+ const result = await validateIrisApp(IrisApp);
387
+ expect(result).toBeNull();
388
+ });
389
+ });
390
+ *
391
+ * @param irisApp Import the index ts(x) file as above and pass it in.
392
+ * @returns null if everything is good - otherwise a string telling you what is wrong.
393
+ */
394
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
395
+ const validateIrisApp = (irisApp) => __awaiter(void 0, void 0, void 0, function* () {
396
+ if (!irisApp.bootstrap || typeof irisApp.bootstrap !== "function") {
397
+ return "Missing a bootstrap function";
398
+ }
399
+ if (!irisApp.mount || typeof irisApp.mount !== "function") {
400
+ return "Missing a mount function";
401
+ }
402
+ if (!irisApp.unmount || typeof irisApp.unmount !== "function") {
403
+ return "Missing an unmount function";
404
+ }
405
+ if (irisApp.update && typeof irisApp.update !== "function") {
406
+ return "Update must be a function";
407
+ }
408
+ return null;
409
+ });
410
+
411
+ exports.MockContextProviderBuilder = MockContextProviderBuilder;
412
+ exports.__awaiter = __awaiter;
413
+ exports.doNothing = doNothing;
414
+ exports.flushPromises = flushPromises;
415
+ exports.flushPromisesInAct = flushPromisesInAct;
416
+ exports.mockCurrentUserContext = mockCurrentUserContext;
417
+ exports.mockEnvironmentContext = mockEnvironmentContext;
418
+ exports.queryFor = queryFor;
419
+ exports.rootContext = rootContext;
420
+ exports.validateIrisApp = validateIrisApp;
package/package.json CHANGED
@@ -1,17 +1,17 @@
1
1
  {
2
2
  "name": "@trackunit/react-core-contexts-test",
3
- "version": "0.1.34",
3
+ "version": "0.1.35-alpha-0b53b6cf53.0",
4
4
  "repository": "https://github.com/Trackunit/manager",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "module": "./index.js",
7
- "main": "./index.js",
7
+ "main": "./index.cjs",
8
8
  "type": "module",
9
9
  "types": "./src/index.d.ts",
10
10
  "dependencies": {
11
- "@apollo/client": "3.6.9",
11
+ "@apollo/client": "3.7.10",
12
12
  "react": "18.2.0",
13
- "@trackunit/react-core-contexts-api": "0.2.19",
14
- "@trackunit/react-core-hooks": "0.2.32",
13
+ "@trackunit/react-core-contexts-api": "0.2.20-alpha-0b53b6cf53.0",
14
+ "@trackunit/react-core-hooks": "0.2.33-alpha-0b53b6cf53.0",
15
15
  "@trackunit/tailwind-styled-components": "0.0.54",
16
16
  "react-router-dom": "6.4.5",
17
17
  "graphql": "15.8.0"