@backstage/test-utils 1.2.2 → 1.2.3-next.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,36 @@
1
1
  # @backstage/test-utils
2
2
 
3
+ ## 1.2.3-next.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 5e238ed56a: The test utility for the plugin context called `MockPluginProvider` has been created. It will be handy in the cases when you use
8
+ `__experimentalConfigure` in your plugin. It is experimental and exported through `@backstage/test-utils/alpha`.
9
+ - c3fa90e184: Updated dependency `zen-observable` to `^0.10.0`.
10
+ - Updated dependencies
11
+ - @backstage/core-app-api@1.2.1-next.1
12
+ - @backstage/core-plugin-api@1.1.1-next.1
13
+ - @backstage/types@1.0.2-next.1
14
+ - @backstage/config@1.0.5-next.1
15
+ - @backstage/plugin-permission-react@0.4.8-next.1
16
+ - @backstage/theme@0.2.16
17
+ - @backstage/plugin-permission-common@0.7.2-next.1
18
+
19
+ ## 1.2.3-next.0
20
+
21
+ ### Patch Changes
22
+
23
+ - 3280711113: Updated dependency `msw` to `^0.49.0`.
24
+ - 19356df560: Updated dependency `zen-observable` to `^0.9.0`.
25
+ - Updated dependencies
26
+ - @backstage/core-app-api@1.2.1-next.0
27
+ - @backstage/core-plugin-api@1.1.1-next.0
28
+ - @backstage/plugin-permission-common@0.7.2-next.0
29
+ - @backstage/types@1.0.2-next.0
30
+ - @backstage/config@1.0.5-next.0
31
+ - @backstage/theme@0.2.16
32
+ - @backstage/plugin-permission-react@0.4.8-next.0
33
+
3
34
  ## 1.2.2
4
35
 
5
36
  ### Patch Changes
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "@backstage/test-utils",
3
+ "version": "1.2.3-next.1",
4
+ "main": "../dist/index.esm.js",
5
+ "types": "../dist/index.alpha.d.ts"
6
+ }
@@ -0,0 +1,516 @@
1
+ /**
2
+ * Utilities to test Backstage plugins and apps.
3
+ *
4
+ * @packageDocumentation
5
+ */
6
+
7
+ import { AnalyticsApi } from '@backstage/core-plugin-api';
8
+ import { AnalyticsEvent } from '@backstage/core-plugin-api';
9
+ import { ApiHolder } from '@backstage/core-plugin-api';
10
+ import { ApiRef } from '@backstage/core-plugin-api';
11
+ import { AuthorizeResult } from '@backstage/plugin-permission-common';
12
+ import { ComponentType } from 'react';
13
+ import { Config } from '@backstage/config';
14
+ import { ConfigApi } from '@backstage/core-plugin-api';
15
+ import crossFetch from 'cross-fetch';
16
+ import { DiscoveryApi } from '@backstage/core-plugin-api';
17
+ import { ErrorApi } from '@backstage/core-plugin-api';
18
+ import { ErrorApiError } from '@backstage/core-plugin-api';
19
+ import { ErrorApiErrorContext } from '@backstage/core-plugin-api';
20
+ import { EvaluatePermissionRequest } from '@backstage/plugin-permission-common';
21
+ import { EvaluatePermissionResponse } from '@backstage/plugin-permission-common';
22
+ import { ExternalRouteRef } from '@backstage/core-plugin-api';
23
+ import { FetchApi } from '@backstage/core-plugin-api';
24
+ import { IdentityApi } from '@backstage/core-plugin-api';
25
+ import { JsonObject } from '@backstage/types';
26
+ import { JsonValue } from '@backstage/types';
27
+ import { Observable } from '@backstage/types';
28
+ import { PermissionApi } from '@backstage/plugin-permission-react';
29
+ import { PropsWithChildren } from 'react';
30
+ import { ReactElement } from 'react';
31
+ import { ReactNode } from 'react';
32
+ import { RenderOptions } from '@testing-library/react';
33
+ import { RenderResult } from '@testing-library/react';
34
+ import { RouteRef } from '@backstage/core-plugin-api';
35
+ import { StorageApi } from '@backstage/core-plugin-api';
36
+ import { StorageValueSnapshot } from '@backstage/core-plugin-api';
37
+
38
+ /**
39
+ * AsyncLogCollector type used in {@link (withLogCollector:1)} callback function.
40
+ * @public
41
+ */
42
+ export declare type AsyncLogCollector = () => Promise<void>;
43
+
44
+ /**
45
+ * Map of severity level and corresponding log lines.
46
+ * @public
47
+ */
48
+ export declare type CollectedLogs<T extends LogFuncs> = {
49
+ [key in T]: string[];
50
+ };
51
+
52
+ /**
53
+ * Creates a Wrapper component that wraps a component inside a Backstage test app,
54
+ * providing a mocked theme and app context, along with mocked APIs.
55
+ *
56
+ * @param options - Additional options for the rendering.
57
+ * @public
58
+ */
59
+ export declare function createTestAppWrapper(options?: TestAppOptions): (props: {
60
+ children: ReactNode;
61
+ }) => JSX.Element;
62
+
63
+ /**
64
+ * ErrorWithContext contains error and ErrorApiErrorContext
65
+ * @public
66
+ */
67
+ export declare type ErrorWithContext = {
68
+ error: ErrorApiError;
69
+ context?: ErrorApiErrorContext;
70
+ };
71
+
72
+ /**
73
+ * Union type used in {@link (withLogCollector:3)} callback function.
74
+ * @public
75
+ */
76
+ export declare type LogCollector = AsyncLogCollector | SyncLogCollector;
77
+
78
+ /**
79
+ * Severity levels of {@link CollectedLogs}
80
+ * @public
81
+ */
82
+ export declare type LogFuncs = 'log' | 'warn' | 'error';
83
+
84
+ /**
85
+ * Mock implementation of {@link core-plugin-api#AnalyticsApi} with helpers to ensure that events are sent correctly.
86
+ * Use getEvents in tests to verify captured events.
87
+ *
88
+ * @public
89
+ */
90
+ export declare class MockAnalyticsApi implements AnalyticsApi {
91
+ private events;
92
+ captureEvent(event: AnalyticsEvent): void;
93
+ getEvents(): AnalyticsEvent[];
94
+ }
95
+
96
+ /**
97
+ * This is a mocking method suggested in the Jest docs, as it is not implemented in JSDOM yet.
98
+ * It can be used to mock values for the MUI `useMediaQuery` hook if it is used in a tested component.
99
+ *
100
+ * For issues checkout the documentation:
101
+ * https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom
102
+ *
103
+ * If there are any updates from MUI React on testing `useMediaQuery` this mock should be replaced
104
+ * https://material-ui.com/components/use-media-query/#testing
105
+ *
106
+ * @public
107
+ */
108
+ export declare function mockBreakpoint(options: {
109
+ matches: boolean;
110
+ }): void;
111
+
112
+ /**
113
+ * MockConfigApi is a thin wrapper around {@link @backstage/config#ConfigReader}
114
+ * that can be used to mock configuration using a plain object.
115
+ *
116
+ * @public
117
+ * @example
118
+ * ```tsx
119
+ * const mockConfig = new MockConfigApi({
120
+ * app: { baseUrl: 'https://example.com' },
121
+ * });
122
+ *
123
+ * const rendered = await renderInTestApp(
124
+ * <TestApiProvider apis={[[configApiRef, mockConfig]]}>
125
+ * <MyTestedComponent />
126
+ * </TestApiProvider>,
127
+ * );
128
+ * ```
129
+ */
130
+ export declare class MockConfigApi implements ConfigApi {
131
+ private readonly config;
132
+ constructor(data: JsonObject);
133
+ /** {@inheritdoc @backstage/config#Config.has} */
134
+ has(key: string): boolean;
135
+ /** {@inheritdoc @backstage/config#Config.keys} */
136
+ keys(): string[];
137
+ /** {@inheritdoc @backstage/config#Config.get} */
138
+ get<T = JsonValue>(key?: string): T;
139
+ /** {@inheritdoc @backstage/config#Config.getOptional} */
140
+ getOptional<T = JsonValue>(key?: string): T | undefined;
141
+ /** {@inheritdoc @backstage/config#Config.getConfig} */
142
+ getConfig(key: string): Config;
143
+ /** {@inheritdoc @backstage/config#Config.getOptionalConfig} */
144
+ getOptionalConfig(key: string): Config | undefined;
145
+ /** {@inheritdoc @backstage/config#Config.getConfigArray} */
146
+ getConfigArray(key: string): Config[];
147
+ /** {@inheritdoc @backstage/config#Config.getOptionalConfigArray} */
148
+ getOptionalConfigArray(key: string): Config[] | undefined;
149
+ /** {@inheritdoc @backstage/config#Config.getNumber} */
150
+ getNumber(key: string): number;
151
+ /** {@inheritdoc @backstage/config#Config.getOptionalNumber} */
152
+ getOptionalNumber(key: string): number | undefined;
153
+ /** {@inheritdoc @backstage/config#Config.getBoolean} */
154
+ getBoolean(key: string): boolean;
155
+ /** {@inheritdoc @backstage/config#Config.getOptionalBoolean} */
156
+ getOptionalBoolean(key: string): boolean | undefined;
157
+ /** {@inheritdoc @backstage/config#Config.getString} */
158
+ getString(key: string): string;
159
+ /** {@inheritdoc @backstage/config#Config.getOptionalString} */
160
+ getOptionalString(key: string): string | undefined;
161
+ /** {@inheritdoc @backstage/config#Config.getStringArray} */
162
+ getStringArray(key: string): string[];
163
+ /** {@inheritdoc @backstage/config#Config.getOptionalStringArray} */
164
+ getOptionalStringArray(key: string): string[] | undefined;
165
+ }
166
+
167
+ /**
168
+ * Mock implementation of the {@link core-plugin-api#ErrorApi} to be used in tests.
169
+ * Includes withForError and getErrors methods for error testing.
170
+ * @public
171
+ */
172
+ export declare class MockErrorApi implements ErrorApi {
173
+ private readonly options;
174
+ private readonly errors;
175
+ private readonly waiters;
176
+ constructor(options?: MockErrorApiOptions);
177
+ post(error: ErrorApiError, context?: ErrorApiErrorContext): void;
178
+ error$(): Observable<{
179
+ error: ErrorApiError;
180
+ context?: ErrorApiErrorContext;
181
+ }>;
182
+ getErrors(): ErrorWithContext[];
183
+ waitForError(pattern: RegExp, timeoutMs?: number): Promise<ErrorWithContext>;
184
+ }
185
+
186
+ /**
187
+ * Constructor arguments for {@link MockErrorApi}
188
+ * @public
189
+ */
190
+ export declare type MockErrorApiOptions = {
191
+ collect?: boolean;
192
+ };
193
+
194
+ /**
195
+ * A test helper implementation of {@link @backstage/core-plugin-api#FetchApi}.
196
+ *
197
+ * @public
198
+ */
199
+ export declare class MockFetchApi implements FetchApi {
200
+ private readonly implementation;
201
+ /**
202
+ * Creates a mock {@link @backstage/core-plugin-api#FetchApi}.
203
+ */
204
+ constructor(options?: MockFetchApiOptions);
205
+ /** {@inheritdoc @backstage/core-plugin-api#FetchApi.fetch} */
206
+ get fetch(): typeof crossFetch;
207
+ }
208
+
209
+ /**
210
+ * The options given when constructing a {@link MockFetchApi}.
211
+ *
212
+ * @public
213
+ */
214
+ export declare interface MockFetchApiOptions {
215
+ /**
216
+ * Define the underlying base `fetch` implementation.
217
+ *
218
+ * @defaultValue undefined
219
+ * @remarks
220
+ *
221
+ * Leaving out this parameter or passing `undefined`, makes the API use the
222
+ * global `fetch` implementation to make real network requests.
223
+ *
224
+ * `'none'` swallows all calls and makes no requests at all.
225
+ *
226
+ * You can also pass in any `fetch` compatible callback, such as a
227
+ * `jest.fn()`, if you want to use a custom implementation or to just track
228
+ * and assert on calls.
229
+ */
230
+ baseImplementation?: undefined | 'none' | typeof crossFetch;
231
+ /**
232
+ * Add translation from `plugin://` URLs to concrete http(s) URLs, basically
233
+ * simulating what
234
+ * {@link @backstage/core-app-api#FetchMiddlewares.resolvePluginProtocol}
235
+ * does.
236
+ *
237
+ * @defaultValue undefined
238
+ * @remarks
239
+ *
240
+ * Leaving out this parameter or passing `undefined`, disables plugin protocol
241
+ * translation.
242
+ *
243
+ * To enable the feature, pass in a discovery API which is then used to
244
+ * resolve the URLs.
245
+ */
246
+ resolvePluginProtocol?: undefined | {
247
+ discoveryApi: Pick<DiscoveryApi, 'getBaseUrl'>;
248
+ };
249
+ /**
250
+ * Add token based Authorization headers to requests, basically simulating
251
+ * what {@link @backstage/core-app-api#FetchMiddlewares.injectIdentityAuth}
252
+ * does.
253
+ *
254
+ * @defaultValue undefined
255
+ * @remarks
256
+ *
257
+ * Leaving out this parameter or passing `undefined`, disables auth injection.
258
+ *
259
+ * To enable the feature, pass in either a static token or an identity API
260
+ * which is queried on each request for a token.
261
+ */
262
+ injectIdentityAuth?: undefined | {
263
+ token: string;
264
+ } | {
265
+ identityApi: Pick<IdentityApi, 'getCredentials'>;
266
+ };
267
+ }
268
+
269
+ /**
270
+ * Mock implementation of
271
+ * {@link @backstage/plugin-permission-react#PermissionApi}. Supply a
272
+ * requestHandler function to override the mock result returned for a given
273
+ * request.
274
+ * @public
275
+ */
276
+ export declare class MockPermissionApi implements PermissionApi {
277
+ private readonly requestHandler;
278
+ constructor(requestHandler?: (request: EvaluatePermissionRequest) => AuthorizeResult.ALLOW | AuthorizeResult.DENY);
279
+ authorize(request: EvaluatePermissionRequest): Promise<EvaluatePermissionResponse>;
280
+ }
281
+
282
+ /**
283
+ * Mock for PluginProvider to use in unit tests
284
+ * @alpha
285
+ */
286
+ export declare const MockPluginProvider: ({ children }: PropsWithChildren<{}>) => JSX.Element;
287
+
288
+ /**
289
+ * Mock implementation of the {@link core-plugin-api#StorageApi} to be used in tests
290
+ * @public
291
+ */
292
+ export declare class MockStorageApi implements StorageApi {
293
+ private readonly namespace;
294
+ private readonly data;
295
+ private readonly bucketStorageApis;
296
+ private constructor();
297
+ static create(data?: MockStorageBucket): MockStorageApi;
298
+ forBucket(name: string): StorageApi;
299
+ snapshot<T extends JsonValue>(key: string): StorageValueSnapshot<T>;
300
+ set<T>(key: string, data: T): Promise<void>;
301
+ remove(key: string): Promise<void>;
302
+ observe$<T>(key: string): Observable<StorageValueSnapshot<T>>;
303
+ private getKeyName;
304
+ private notifyChanges;
305
+ private subscribers;
306
+ private readonly observable;
307
+ }
308
+
309
+ /**
310
+ * Type for map holding data in {@link MockStorageApi}
311
+ * @public
312
+ */
313
+ export declare type MockStorageBucket = {
314
+ [key: string]: any;
315
+ };
316
+
317
+ /**
318
+ * Renders a component inside a Backstage test app, providing a mocked theme
319
+ * and app context, along with mocked APIs.
320
+ *
321
+ * The render executes async effects similar to `renderWithEffects`. To avoid this
322
+ * behavior, use a regular `render()` + `wrapInTestApp()` instead.
323
+ *
324
+ * @param Component - A component or react node to render inside the test app.
325
+ * @param options - Additional options for the rendering.
326
+ * @public
327
+ */
328
+ export declare function renderInTestApp(Component: ComponentType | ReactNode, options?: TestAppOptions): Promise<RenderResult>;
329
+
330
+ /**
331
+ * @public
332
+ * Simplifies rendering of async components in by taking care of the wrapping inside act
333
+ *
334
+ * @remarks
335
+ *
336
+ * Components using useEffect to perform an asynchronous action (such as fetch) must be rendered within an async
337
+ * act call to properly get the final state, even with mocked responses. This utility method makes the signature a bit
338
+ * cleaner, since act doesn't return the result of the evaluated function.
339
+ * https://github.com/testing-library/react-testing-library/issues/281
340
+ * https://github.com/facebook/react/pull/14853
341
+ */
342
+ export declare function renderWithEffects(nodes: ReactElement, options?: Pick<RenderOptions, 'wrapper'>): Promise<RenderResult>;
343
+
344
+ /**
345
+ * Sets up handlers for request mocking
346
+ * @public
347
+ * @param worker - service worker
348
+ */
349
+ export declare function setupRequestMockHandlers(worker: {
350
+ listen: (t: any) => void;
351
+ close: () => void;
352
+ resetHandlers: () => void;
353
+ }): void;
354
+
355
+ /**
356
+ * SyncLogCollector type used in {@link (withLogCollector:2)} callback function.
357
+ * @public
358
+ */
359
+ export declare type SyncLogCollector = () => void;
360
+
361
+ /**
362
+ * The `TestApiProvider` is a Utility API context provider that is particularly
363
+ * well suited for development and test environments such as unit tests, storybooks,
364
+ * and isolated plugin development setups.
365
+ *
366
+ * It lets you provide any number of API implementations, without necessarily
367
+ * having to fully implement each of the APIs.
368
+ *
369
+ * A migration from `ApiRegistry` and `ApiProvider` might look like this, from:
370
+ *
371
+ * ```tsx
372
+ * renderInTestApp(
373
+ * <ApiProvider
374
+ * apis={ApiRegistry.from([
375
+ * [identityApiRef, mockIdentityApi as unknown as IdentityApi]
376
+ * ])}
377
+ * >
378
+ * {...}
379
+ * </ApiProvider>
380
+ * )
381
+ * ```
382
+ *
383
+ * To the following:
384
+ *
385
+ * ```tsx
386
+ * renderInTestApp(
387
+ * <TestApiProvider apis={[[identityApiRef, mockIdentityApi]]}>
388
+ * {...}
389
+ * </TestApiProvider>
390
+ * )
391
+ * ```
392
+ *
393
+ * Note that the cast to `IdentityApi` is no longer needed as long as the mock API
394
+ * implements a subset of the `IdentityApi`.
395
+ *
396
+ * @public
397
+ **/
398
+ export declare const TestApiProvider: <T extends any[]>(props: TestApiProviderProps<T>) => JSX.Element;
399
+
400
+ /**
401
+ * Properties for the {@link TestApiProvider} component.
402
+ *
403
+ * @public
404
+ */
405
+ export declare type TestApiProviderProps<TApiPairs extends any[]> = {
406
+ apis: readonly [...TestApiProviderPropsApiPairs<TApiPairs>];
407
+ children: ReactNode;
408
+ };
409
+
410
+ /** @ignore */
411
+ declare type TestApiProviderPropsApiPair<TApi> = TApi extends infer TImpl ? readonly [ApiRef<TApi>, Partial<TImpl>] : never;
412
+
413
+ /** @ignore */
414
+ declare type TestApiProviderPropsApiPairs<TApiPairs> = {
415
+ [TIndex in keyof TApiPairs]: TestApiProviderPropsApiPair<TApiPairs[TIndex]>;
416
+ };
417
+
418
+ /**
419
+ * The `TestApiRegistry` is an {@link @backstage/core-plugin-api#ApiHolder} implementation
420
+ * that is particularly well suited for development and test environments such as
421
+ * unit tests, storybooks, and isolated plugin development setups.
422
+ *
423
+ * @public
424
+ */
425
+ export declare class TestApiRegistry implements ApiHolder {
426
+ private readonly apis;
427
+ /**
428
+ * Creates a new {@link TestApiRegistry} with a list of API implementation pairs.
429
+ *
430
+ * Similar to the {@link TestApiProvider}, there is no need to provide a full
431
+ * implementation of each API, it's enough to implement the methods that are tested.
432
+ *
433
+ * @example
434
+ * ```ts
435
+ * const apis = TestApiRegistry.from(
436
+ * [configApiRef, new ConfigReader({})],
437
+ * [identityApiRef, { getUserId: () => 'tester' }],
438
+ * );
439
+ * ```
440
+ *
441
+ * @public
442
+ * @param apis - A list of pairs mapping an ApiRef to its respective implementation.
443
+ */
444
+ static from<TApiPairs extends any[]>(...apis: readonly [...TestApiProviderPropsApiPairs<TApiPairs>]): TestApiRegistry;
445
+ private constructor();
446
+ /**
447
+ * Returns an implementation of the API.
448
+ *
449
+ * @public
450
+ */
451
+ get<T>(api: ApiRef<T>): T | undefined;
452
+ }
453
+
454
+ /**
455
+ * Options to customize the behavior of the test app wrapper.
456
+ * @public
457
+ */
458
+ export declare type TestAppOptions = {
459
+ /**
460
+ * Initial route entries to pass along as `initialEntries` to the router.
461
+ */
462
+ routeEntries?: string[];
463
+ /**
464
+ * An object of paths to mount route ref on, with the key being the path and the value
465
+ * being the RouteRef that the path will be bound to. This allows the route refs to be
466
+ * used by `useRouteRef` in the rendered elements.
467
+ *
468
+ * @example
469
+ * wrapInTestApp(<MyComponent />, \{
470
+ * mountedRoutes: \{
471
+ * '/my-path': myRouteRef,
472
+ * \}
473
+ * \})
474
+ * // ...
475
+ * const link = useRouteRef(myRouteRef)
476
+ */
477
+ mountedRoutes?: {
478
+ [path: string]: RouteRef | ExternalRouteRef;
479
+ };
480
+ };
481
+
482
+ /**
483
+ * Asynchronous log collector with that collects all categories
484
+ * @public
485
+ */
486
+ export declare function withLogCollector(callback: AsyncLogCollector): Promise<CollectedLogs<LogFuncs>>;
487
+
488
+ /**
489
+ * Synchronous log collector with that collects all categories
490
+ * @public
491
+ */
492
+ export declare function withLogCollector(callback: SyncLogCollector): CollectedLogs<LogFuncs>;
493
+
494
+ /**
495
+ * Asynchronous log collector with that only collects selected categories
496
+ * @public
497
+ */
498
+ export declare function withLogCollector<T extends LogFuncs>(logsToCollect: T[], callback: AsyncLogCollector): Promise<CollectedLogs<T>>;
499
+
500
+ /**
501
+ * Synchronous log collector with that only collects selected categories
502
+ * @public
503
+ */
504
+ export declare function withLogCollector<T extends LogFuncs>(logsToCollect: T[], callback: SyncLogCollector): CollectedLogs<T>;
505
+
506
+ /**
507
+ * Wraps a component inside a Backstage test app, providing a mocked theme
508
+ * and app context, along with mocked APIs.
509
+ *
510
+ * @param Component - A component or react node to render inside the test app.
511
+ * @param options - Additional options for the rendering.
512
+ * @public
513
+ */
514
+ export declare function wrapInTestApp(Component: ComponentType | ReactNode, options?: TestAppOptions): ReactElement;
515
+
516
+ export { }