@dr.pogodin/react-utils 1.47.0-alpha.7 → 1.47.0-alpha.9

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.
Files changed (165) hide show
  1. package/build/development/client/index.js +1 -1
  2. package/build/development/client/index.js.map +1 -1
  3. package/build/development/index.js +1 -11
  4. package/build/development/index.js.map +1 -1
  5. package/build/development/server/index.js +3 -6
  6. package/build/development/server/index.js.map +1 -1
  7. package/build/development/server/utils/index.js +1 -1
  8. package/build/development/server/utils/index.js.map +1 -1
  9. package/build/development/shared/components/Button/index.js +1 -1
  10. package/build/development/shared/components/Button/index.js.map +1 -1
  11. package/build/development/shared/components/Checkbox/index.js +1 -1
  12. package/build/development/shared/components/Checkbox/index.js.map +1 -1
  13. package/build/development/shared/components/Input/index.js +1 -1
  14. package/build/development/shared/components/Input/index.js.map +1 -1
  15. package/build/development/shared/components/Modal/index.js +1 -1
  16. package/build/development/shared/components/Modal/index.js.map +1 -1
  17. package/build/development/shared/components/PageLayout/index.js +1 -1
  18. package/build/development/shared/components/PageLayout/index.js.map +1 -1
  19. package/build/development/shared/components/TextArea/index.js +1 -1
  20. package/build/development/shared/components/TextArea/index.js.map +1 -1
  21. package/build/development/shared/components/Throbber/index.js +1 -1
  22. package/build/development/shared/components/Throbber/index.js.map +1 -1
  23. package/build/development/shared/components/WithTooltip/index.js +1 -1
  24. package/build/development/shared/components/WithTooltip/index.js.map +1 -1
  25. package/build/development/shared/components/YouTubeVideo/index.js +1 -1
  26. package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
  27. package/build/development/shared/components/selectors/CustomDropdown/index.js +1 -1
  28. package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  29. package/build/development/shared/components/selectors/NativeDropdown/index.js +1 -1
  30. package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  31. package/build/development/shared/components/selectors/Switch/index.js +1 -1
  32. package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
  33. package/build/production/client/index.js +1 -1
  34. package/build/production/client/index.js.map +1 -1
  35. package/build/production/index.js +2 -6
  36. package/build/production/index.js.map +1 -1
  37. package/build/production/server/index.js +3 -3
  38. package/build/production/server/index.js.map +1 -1
  39. package/build/production/server/utils/index.js +1 -1
  40. package/build/production/server/utils/index.js.map +1 -1
  41. package/build/production/shared/components/Button/index.js +1 -1
  42. package/build/production/shared/components/Button/index.js.map +1 -1
  43. package/build/production/shared/components/Checkbox/index.js +1 -1
  44. package/build/production/shared/components/Checkbox/index.js.map +1 -1
  45. package/build/production/shared/components/Input/index.js +1 -1
  46. package/build/production/shared/components/Input/index.js.map +1 -1
  47. package/build/production/shared/components/Modal/index.js +1 -1
  48. package/build/production/shared/components/Modal/index.js.map +1 -1
  49. package/build/production/shared/components/PageLayout/index.js +1 -1
  50. package/build/production/shared/components/PageLayout/index.js.map +1 -1
  51. package/build/production/shared/components/TextArea/index.js +1 -1
  52. package/build/production/shared/components/TextArea/index.js.map +1 -1
  53. package/build/production/shared/components/Throbber/index.js +1 -1
  54. package/build/production/shared/components/Throbber/index.js.map +1 -1
  55. package/build/production/shared/components/WithTooltip/index.js +1 -1
  56. package/build/production/shared/components/WithTooltip/index.js.map +1 -1
  57. package/build/production/shared/components/YouTubeVideo/index.js +1 -1
  58. package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
  59. package/build/production/shared/components/selectors/CustomDropdown/index.js +1 -1
  60. package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  61. package/build/production/shared/components/selectors/NativeDropdown/index.js +1 -1
  62. package/build/production/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  63. package/build/production/shared/components/selectors/Switch/index.js +1 -1
  64. package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
  65. package/build/types-code/client/index.d.ts +1 -1
  66. package/build/types-code/index.d.ts +0 -6
  67. package/build/types-code/server/index.d.ts +4 -9
  68. package/build/types-code/server/utils/index.d.ts +1 -1
  69. package/build/web/client/index.js +1 -1
  70. package/build/web/client/index.js.map +1 -1
  71. package/build/web/index.js +0 -12
  72. package/build/web/index.js.map +1 -1
  73. package/build/web/server/index.js +3 -6
  74. package/build/web/server/index.js.map +1 -1
  75. package/build/web/server/utils/index.js +1 -1
  76. package/build/web/server/utils/index.js.map +1 -1
  77. package/build/web/shared/components/Button/index.js +1 -1
  78. package/build/web/shared/components/Button/index.js.map +1 -1
  79. package/build/web/shared/components/Checkbox/index.js +1 -1
  80. package/build/web/shared/components/Checkbox/index.js.map +1 -1
  81. package/build/web/shared/components/Input/index.js +1 -1
  82. package/build/web/shared/components/Input/index.js.map +1 -1
  83. package/build/web/shared/components/Modal/index.js +1 -1
  84. package/build/web/shared/components/Modal/index.js.map +1 -1
  85. package/build/web/shared/components/PageLayout/index.js +1 -1
  86. package/build/web/shared/components/PageLayout/index.js.map +1 -1
  87. package/build/web/shared/components/TextArea/index.js +1 -1
  88. package/build/web/shared/components/TextArea/index.js.map +1 -1
  89. package/build/web/shared/components/Throbber/index.js +1 -1
  90. package/build/web/shared/components/Throbber/index.js.map +1 -1
  91. package/build/web/shared/components/WithTooltip/index.js +1 -1
  92. package/build/web/shared/components/WithTooltip/index.js.map +1 -1
  93. package/build/web/shared/components/YouTubeVideo/index.js +1 -1
  94. package/build/web/shared/components/YouTubeVideo/index.js.map +1 -1
  95. package/build/web/shared/components/selectors/CustomDropdown/index.js +1 -1
  96. package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -1
  97. package/build/web/shared/components/selectors/NativeDropdown/index.js +1 -1
  98. package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -1
  99. package/build/web/shared/components/selectors/Switch/index.js +1 -1
  100. package/build/web/shared/components/selectors/Switch/index.js.map +1 -1
  101. package/package.json +17 -6
  102. package/src/client/getInj.ts +0 -71
  103. package/src/client/index.tsx +0 -45
  104. package/src/client/init.ts +0 -52
  105. package/src/index.ts +0 -75
  106. package/src/server/Cache.ts +0 -61
  107. package/src/server/index.ts +0 -243
  108. package/src/server/renderer.tsx +0 -635
  109. package/src/server/server.ts +0 -330
  110. package/src/server/utils/errors.ts +0 -122
  111. package/src/server/utils/index.ts +0 -3
  112. package/src/shared/components/Button/index.tsx +0 -130
  113. package/src/shared/components/Button/style.scss +0 -54
  114. package/src/shared/components/Checkbox/index.tsx +0 -53
  115. package/src/shared/components/Checkbox/theme.scss +0 -63
  116. package/src/shared/components/GenericLink/index.tsx +0 -141
  117. package/src/shared/components/GenericLink/style.scss +0 -3
  118. package/src/shared/components/Input/index.tsx +0 -96
  119. package/src/shared/components/Input/theme.scss +0 -52
  120. package/src/shared/components/Link.tsx +0 -25
  121. package/src/shared/components/Modal/base-theme.scss +0 -38
  122. package/src/shared/components/Modal/index.tsx +0 -177
  123. package/src/shared/components/Modal/styles.scss +0 -3
  124. package/src/shared/components/NavLink.tsx +0 -18
  125. package/src/shared/components/PageLayout/base-theme.scss +0 -30
  126. package/src/shared/components/PageLayout/index.tsx +0 -51
  127. package/src/shared/components/TextArea/index.tsx +0 -139
  128. package/src/shared/components/TextArea/style.scss +0 -68
  129. package/src/shared/components/Throbber/index.tsx +0 -28
  130. package/src/shared/components/Throbber/theme.scss +0 -26
  131. package/src/shared/components/WithTooltip/Tooltip.tsx +0 -274
  132. package/src/shared/components/WithTooltip/default-theme.scss +0 -36
  133. package/src/shared/components/WithTooltip/index.tsx +0 -186
  134. package/src/shared/components/YouTubeVideo/base.scss +0 -15
  135. package/src/shared/components/YouTubeVideo/index.tsx +0 -73
  136. package/src/shared/components/YouTubeVideo/throbber.scss +0 -11
  137. package/src/shared/components/index.ts +0 -20
  138. package/src/shared/components/selectors/CustomDropdown/Options/index.tsx +0 -124
  139. package/src/shared/components/selectors/CustomDropdown/Options/style.scss +0 -6
  140. package/src/shared/components/selectors/CustomDropdown/index.tsx +0 -146
  141. package/src/shared/components/selectors/CustomDropdown/theme.scss +0 -118
  142. package/src/shared/components/selectors/NativeDropdown/index.tsx +0 -90
  143. package/src/shared/components/selectors/NativeDropdown/theme.scss +0 -81
  144. package/src/shared/components/selectors/Switch/index.tsx +0 -74
  145. package/src/shared/components/selectors/Switch/theme.scss +0 -39
  146. package/src/shared/components/selectors/common.ts +0 -57
  147. package/src/shared/components/selectors/index.ts +0 -8
  148. package/src/shared/utils/config.ts +0 -59
  149. package/src/shared/utils/globalState.ts +0 -44
  150. package/src/shared/utils/index.ts +0 -45
  151. package/src/shared/utils/isomorphy/buildInfo.ts +0 -50
  152. package/src/shared/utils/isomorphy/environment-check.ts +0 -18
  153. package/src/shared/utils/isomorphy/index.ts +0 -36
  154. package/src/shared/utils/jest/E2eSsrEnv.ts +0 -304
  155. package/src/shared/utils/jest/global.ts +0 -17
  156. package/src/shared/utils/jest/index.ts +0 -215
  157. package/src/shared/utils/splitComponent.tsx +0 -284
  158. package/src/shared/utils/time.ts +0 -101
  159. package/src/shared/utils/webpack.ts +0 -80
  160. package/src/styles/_global/reset.css +0 -52
  161. package/src/styles/_mixins/fonts.scss +0 -40
  162. package/src/styles/_mixins/media.scss +0 -150
  163. package/src/styles/_mixins/typography.scss +0 -83
  164. package/src/styles/global.scss +0 -11
  165. package/src/styles/mixins.scss +0 -6
@@ -1,304 +0,0 @@
1
- /**
2
- * Jest environment for end-to-end SSR and client-side testing. It relies on
3
- * the standard react-utils mechanics to execute SSR of given scene, and also
4
- * Webpack build of the code for client-side execution, it further exposes
5
- * Jsdom environment for the client-side testing of the outcomes.
6
- */
7
-
8
- // BEWARE: The module is not imported into the JU module / the main assembly of
9
- // the library, because doing so easily breaks stuff:
10
- // 1) This module depends on Node-specific modules, which would make JU
11
- // incompatible with JsDom if included into JU.
12
- // 2) If this module is weakly imported from somewhere else in the lib,
13
- // it seems to randomly break tests using it for a different reason,
14
- // probably some sort of a require-loop, or some issues with weak
15
- // require in that scenario.
16
-
17
- // TODO: We need to add correct typing for environment options.
18
-
19
- import path from 'node:path';
20
-
21
- import type { Request, Response } from 'express';
22
-
23
- import { defaults, set } from 'lodash-es';
24
-
25
- import type { ReactNode } from 'react';
26
-
27
- // As this environment is a part of the Jest testing utils,
28
- // we assume development dependencies are available when it is used.
29
- /* eslint-disable import/no-extraneous-dependencies */
30
- import register from '@babel/register/experimental-worker';
31
-
32
- import JsdomEnv from 'jest-environment-jsdom';
33
- import { Volume, createFsFromVolume } from 'memfs';
34
- import webpack, { type Configuration } from 'webpack';
35
- /* eslint-enable import/no-extraneous-dependencies */
36
-
37
- import type {
38
- EnvironmentContext,
39
- JestEnvironmentConfig,
40
- } from '@jest/environment';
41
-
42
- import ssrFactory from 'server/renderer';
43
-
44
- import { setBuildInfo } from '../isomorphy/buildInfo';
45
-
46
- function noop() {
47
- // NOOP
48
- }
49
-
50
- export default class E2eSsrEnv extends JsdomEnv {
51
- pragmas: Record<string, string | string[]>;
52
-
53
- ssrRequest: object;
54
-
55
- rootDir: string;
56
-
57
- testFolder: string;
58
-
59
- withSsr: boolean;
60
-
61
- webpackStats?: webpack.StatsCompilation;
62
-
63
- /**
64
- * Loads Webpack config, and exposes it to the environment via global
65
- * webpackConfig object.
66
- */
67
- private loadWebpackConfig() {
68
- const optionsString = this.pragmas['webpack-config-options'] as string;
69
-
70
- const options = (optionsString ? JSON.parse(optionsString) : {}) as
71
- webpack.Configuration;
72
-
73
- defaults(options, {
74
- context: this.testFolder,
75
- fs: this.global.webpackOutputFs,
76
- });
77
-
78
- const factoryPath = this.pragmas['webpack-config-factory'] as string;
79
- // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports
80
- let factory = require(path.resolve(this.rootDir, factoryPath)) as
81
- (((ops: Configuration) => Configuration) | {
82
- default: (ops: Configuration) => Configuration;
83
- });
84
- factory = 'default' in factory ? factory.default : factory;
85
-
86
- this.global.webpackConfig = factory(options);
87
-
88
- const fs = this.global.webpackOutputFs;
89
- let buildInfo = `${options.context}/.build-info`;
90
- if (fs.existsSync(buildInfo)) {
91
- buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;
92
- this.global.buildInfo = JSON.parse(buildInfo);
93
- }
94
- }
95
-
96
- /**
97
- * Executes Webpack build.
98
- * @return {Promise}
99
- */
100
- async runWebpack(): Promise<void> {
101
- this.loadWebpackConfig();
102
-
103
- if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');
104
- const compiler = webpack(this.global.webpackConfig);
105
- if (!compiler) throw Error('Failed to construct Webpack compiler');
106
-
107
- // TODO: The "as typeof compiler.outputFileSystem" piece below is
108
- // a workaround for the Webpack regression:
109
- // https://github.com/webpack/webpack/issues/18242
110
- compiler.outputFileSystem = this.global.webpackOutputFs as
111
- typeof compiler.outputFileSystem;
112
-
113
- return new Promise<void>((done, fail) => {
114
- compiler.run((err, stats) => {
115
- if (err) fail(err);
116
- if (stats?.hasErrors()) {
117
- // eslint-disable-next-line no-console
118
- console.error(stats.toJson().errors);
119
- fail(Error('Webpack compilation failed'));
120
- }
121
-
122
- this.global.webpackStats = stats?.toJson();
123
-
124
- // Keeps reference to the raw Webpack stats object, which should be
125
- // explicitly passed to the server-side renderer alongside the request,
126
- // so that it can to pick up asset paths for different named chunks.
127
- this.webpackStats = stats;
128
-
129
- done();
130
- });
131
- });
132
- }
133
-
134
- async runSsr(): Promise<void> {
135
- const optionsString = this.pragmas['ssr-options'] as string;
136
- const options = optionsString
137
- ? JSON.parse(optionsString) as Record<string, unknown>
138
- : {};
139
-
140
- // TODO: This is temporary to shortcut the logging added to SSR.
141
- options.logger ??= {
142
- debug: noop,
143
- info: noop,
144
- log: noop,
145
- warn: noop,
146
- };
147
-
148
- options.buildInfo ??= this.global.buildInfo;
149
-
150
- let cleanup: (() => void) | undefined;
151
-
152
- if (options.entry) {
153
- const p = path.resolve(this.testFolder, options.entry as string);
154
- // TODO: This sure can be replaced by a dynamic import().
155
- // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports
156
- const module = require(p) as NodeJS.Module;
157
- if ('cleanup' in module) cleanup = module.cleanup as () => void;
158
-
159
- const exportName = (options.entryExportName as string) || 'default';
160
- if (exportName in module) {
161
- options.Application = (
162
- module as unknown as Record<string, unknown>
163
- )[exportName] as ReactNode;
164
- }
165
- }
166
-
167
- const renderer = ssrFactory(this.global.webpackConfig!, options);
168
- let status = 200; // OK
169
- const markup = await new Promise<string>((done, fail) => {
170
- void renderer(
171
- this.ssrRequest as Request,
172
-
173
- // TODO: This will do for now, with the current implementation of
174
- // the renderer, but it will require a rework once the renderer is
175
- // updated to do streaming.
176
- ({
177
- cookie: noop,
178
- send: done,
179
- set: noop,
180
- status: (value: number) => {
181
- status = value;
182
- },
183
-
184
- // This is how up-to-date Webpack stats are passed to the server in
185
- // development mode, and we use this here always, instead of having
186
- // to pass some information via filesystem.
187
- locals: {
188
- webpack: {
189
- devMiddleware: {
190
- stats: this.webpackStats,
191
- },
192
- },
193
- },
194
- } as unknown) as Response,
195
-
196
- (error) => {
197
- // TODO: Strictly speaking, that error as Error casting is not all
198
- // correct, but it works, so no need to spend time on it right now.
199
- if (error) fail(error as Error);
200
- else done('');
201
- },
202
- );
203
- });
204
-
205
- this.global.ssrMarkup = markup;
206
- this.global.ssrOptions = options;
207
- this.global.ssrStatus = status;
208
-
209
- if (cleanup) cleanup();
210
- }
211
-
212
- constructor(
213
- config: JestEnvironmentConfig,
214
- context: EnvironmentContext,
215
- ) {
216
- const pragmas = context.docblockPragmas;
217
-
218
- const requestString = pragmas['ssr-request'] as string;
219
- const request = requestString
220
- ? JSON.parse(requestString) as Record<string, unknown>
221
- : {};
222
-
223
- request.url ??= '/';
224
- request.csrfToken = noop;
225
-
226
- // This ensures the initial JsDom URL matches the value we use for SSR.
227
- set(
228
- config.projectConfig,
229
- 'testEnvironmentOptions.url',
230
- `http://localhost${request.url as string}`,
231
- );
232
-
233
- super(config, context);
234
-
235
- this.global.dom = this.dom;
236
- this.global.webpackOutputFs = createFsFromVolume(new Volume());
237
-
238
- // Extracts necessary settings from config and context.
239
- const { projectConfig } = config;
240
- this.rootDir = projectConfig.rootDir;
241
- this.testFolder = path.dirname(context.testPath);
242
- this.withSsr = !pragmas['no-ssr'];
243
- this.ssrRequest = request;
244
- this.pragmas = pragmas;
245
-
246
- // The usual "babel-jest" transformation setup does not apply to
247
- // the environment code and imports from it, this workaround enables it.
248
- const optionsString = this.pragmas['ssr-options'] as string;
249
- const options = optionsString
250
- ? JSON.parse(optionsString) as Record<string, unknown>
251
- : {};
252
- let root;
253
- switch (options.root) {
254
- case 'TEST':
255
- root = this.testFolder;
256
- break;
257
- default: root = process.cwd();
258
- }
259
- register({
260
- envName: options.babelEnv as string,
261
- extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],
262
- root,
263
- });
264
- }
265
-
266
- async setup(): Promise<void> {
267
- await super.setup();
268
- await this.runWebpack();
269
-
270
- // NOTE: It is possible that the Webpack run above, and the SSR run below
271
- // load different versions of the same module (CommonJS, and ES), and it may
272
- // cause very confusing problems (e.g. see:
273
- // https://github.com/birdofpreyru/react-utils/issues/413).
274
- // It seems we can't reset the cache of ES modules, and Jest's module reset
275
- // does not reset modules loaded in this enviroment module, and also only
276
- // replacing entire cache object by and empty {} seems to help (in contrast
277
- // to deleting all entries by their keys, as it is done within .teardown()
278
- // method below). Thus, for now we do this as a hotfix, and we also reset
279
- // build info to undefined, because ES module version not beeing reset
280
- // triggers an error on the subsequent test using the environment.
281
- // TODO: Look for a cleaner solution.
282
- require.cache = {};
283
- setBuildInfo(undefined, true);
284
-
285
- if (this.withSsr) await this.runSsr();
286
- this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;
287
- }
288
-
289
- async teardown(): Promise<void> {
290
- delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;
291
-
292
- // Resets module cache and @babel/register. Effectively this ensures that
293
- // the next time an instance of this environment is set up, all modules are
294
- // transformed by Babel from scratch, thus taking into account the latest
295
- // Babel config (which may change between different environment instances,
296
- // which does not seem to be taken into account by Babel / Node caches
297
- // automatically).
298
- Object.keys(require.cache).forEach((key) => {
299
- delete require.cache[key];
300
- });
301
- register.revert();
302
- await super.teardown();
303
- }
304
- }
@@ -1,17 +0,0 @@
1
- import type { IFs } from 'memfs';
2
- import type { Configuration, StatsCompilation } from 'webpack';
3
-
4
- declare global {
5
- // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
6
- interface Window {
7
- ssrMarkup: string | undefined;
8
- ssrStatus: number | undefined;
9
- webpackConfig: Configuration | undefined;
10
- webpackOutputFs: IFs;
11
- webpackStats?: StatsCompilation;
12
- }
13
- }
14
-
15
- export default function getGlobal(): Window {
16
- return global as unknown as Window;
17
- }
@@ -1,215 +0,0 @@
1
- /* global jest, document */
2
- /* eslint-disable import/no-extraneous-dependencies */
3
-
4
- import type {
5
- AxiosRequestConfig,
6
- AxiosResponse,
7
- AxiosStatic,
8
- InternalAxiosRequestConfig,
9
- } from 'axios';
10
-
11
- import mockdate from 'mockdate';
12
- import { type ReactElement, type ReactNode, act } from 'react';
13
- import { type Root, createRoot } from 'react-dom/client';
14
-
15
- import { type RenderResult, render } from '@testing-library/react';
16
-
17
- /**
18
- * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)
19
- * from `react`.
20
- */
21
- export { act };
22
-
23
- export { default as getGlobal } from './global';
24
-
25
- global.IS_REACT_ACT_ENVIRONMENT = true;
26
-
27
- const originalProcessVersions = process.versions;
28
-
29
- /**
30
- * Tricks **react-utils** into thinking the test is running within client-side
31
- * (browser) environment.
32
- */
33
- export function mockClientSide(): void {
34
- Object.defineProperty(process, 'versions', { value: undefined });
35
- }
36
-
37
- /**
38
- * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.
39
- */
40
- export function unmockClientSide(): void {
41
- Object.defineProperty(process, 'versions', {
42
- value: originalProcessVersions,
43
- writable: false,
44
- });
45
- }
46
-
47
- /**
48
- * Generates a mock UUID, or better said it determenistically transforms given
49
- * `seed` number into a UUID-formatted string.
50
- * @param {number} seed
51
- * @return {string}
52
- */
53
- export function getMockUuid(seed = 0): string {
54
- const x = seed.toString(16).padStart(32, '0');
55
- return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;
56
- }
57
-
58
- export type AxiosRequestHandlerT = (
59
- config: AxiosRequestConfig,
60
- ) => Partial<AxiosResponse> | null | undefined;
61
-
62
- export function mockAxios(handlers: AxiosRequestHandlerT[]): AxiosStatic {
63
- const axios: AxiosStatic = jest.requireActual('axios');
64
-
65
- axios.defaults.adapter = async (
66
- config: AxiosRequestConfig,
67
- ): Promise<AxiosResponse> => {
68
- for (const handler of handlers) {
69
- const res = handler(config);
70
- if (res) {
71
- return {
72
- config: config as InternalAxiosRequestConfig,
73
- data: null,
74
- headers: {},
75
- status: 200,
76
- statusText: 'OK',
77
- ...res,
78
- };
79
- }
80
- }
81
-
82
- // Fallback to the regular network request.
83
- let res: AxiosResponse;
84
- try {
85
- res = await axios({ ...config, adapter: ['xhr', 'http', 'fetch'] });
86
- // eslint-disable-next-line no-console
87
- console.warn(
88
- 'Network request has not been mocked for a test.\n\nConfig:\n',
89
- config,
90
- '\n\nResult:\n',
91
- JSON.stringify(res, null, 2),
92
- );
93
- } catch (e) {
94
- // eslint-disable-next-line no-console
95
- console.warn(
96
- 'Network request has not been mocked for a test, and failed.\n\nConfig:\n',
97
- config,
98
- '\n\nError\n',
99
- JSON.stringify(e, null, 2),
100
- );
101
- throw e;
102
- }
103
-
104
- return res;
105
- };
106
-
107
- return axios;
108
- }
109
-
110
- /**
111
- * Advances mock timers, and mock date by the specified time.
112
- * @param {number} time Time step [ms].
113
- * @returns {Promise} Wait for this to "jump after" any async code which should
114
- * be executed because of the mock time movement.
115
- */
116
- export async function mockTimer(time: number): Promise<void> {
117
- mockdate.set(time + Date.now());
118
- await jest.advanceTimersByTimeAsync(time);
119
- }
120
-
121
- export type MountedSceneT = HTMLElement & {
122
- destroy: () => void;
123
- snapshot: () => void;
124
- };
125
-
126
- /**
127
- * Mounts `scene` to the DOM, and returns the root scene element.
128
- * @param scene
129
- * @return Created container DOM element with destroy() function
130
- * attached.
131
- */
132
- export function mount(scene: ReactNode): MountedSceneT {
133
- let root: Root;
134
- const element = document.createElement('div');
135
- document.body.appendChild(element);
136
-
137
- const res: MountedSceneT = (element as unknown) as MountedSceneT;
138
- res.destroy = () => {
139
- // NOTE: As it seems @testing-library may reset this flag to false
140
- // when it is simulating user events.
141
- global.IS_REACT_ACT_ENVIRONMENT = true;
142
-
143
- act(() => {
144
- root.unmount();
145
- });
146
- res.remove();
147
- };
148
-
149
- res.snapshot = () => {
150
- expect(res).toMatchSnapshot();
151
- };
152
-
153
- // NOTE: As it seems @testing-library may reset this flag to false
154
- // when it is simulating user events.
155
- global.IS_REACT_ACT_ENVIRONMENT = true;
156
-
157
- act(() => {
158
- root = createRoot(res);
159
- root.render(scene);
160
- });
161
- return res;
162
- }
163
-
164
- // NOTE: If in future we have additional options here, they should be distributed
165
- // across two objects, depending whether they are applicable to the sync, or async
166
- // versions of snapshot(), or both.
167
- type AsyncSnapshotOptionsT = {
168
- await?: Promise<void>;
169
- };
170
-
171
- export function snapshot(element: ReactElement): RenderResult;
172
-
173
- export async function snapshot(
174
- element: ReactElement,
175
- options: AsyncSnapshotOptionsT,
176
- ): Promise<RenderResult>;
177
-
178
- export function snapshot(
179
- element: React.ReactElement,
180
- options?: AsyncSnapshotOptionsT,
181
- ): Promise<RenderResult> | RenderResult {
182
- let res: RenderResult | undefined;
183
-
184
- // TODO: Just adding async to the actor function breaks stuff, as it makes
185
- // act() asynchronous no matter the `options.await` value, thus breaking all
186
- // calls that do not await for snapshot() result... thus... perhaps we need
187
- // to have a more complex typing to ensure it all works as intended in all
188
- // cases, and while being correctly enforced by TypeScript.
189
- // eslint-disable-next-line @typescript-eslint/promise-function-async
190
- const promise = act(() => {
191
- res = render(element);
192
- return options?.await;
193
- });
194
-
195
- if (res === undefined) throw Error('Render failed');
196
- if (options?.await) {
197
- // BEWARE: Although `promise` is thenable (i.e. it has .then() method),
198
- // it is not an instance of proper Promise class, and returning it directly
199
- // breaks some async logic in Jest test or React test functions... thus, we
200
- // wrap it into Promise instance here.
201
- return new Promise((resolve) => {
202
- void promise.then(() => {
203
- // TODO: These lines are the same as the lines below for sync variant of
204
- // the function. We should split and reuse them in both places.
205
- const nodes = res!.asFragment().childNodes;
206
- expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();
207
- resolve(res!);
208
- });
209
- });
210
- }
211
-
212
- const nodes = res.asFragment().childNodes;
213
- expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();
214
- return res;
215
- }