@backstage/test-utils 1.2.3-next.0 → 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.
@@ -0,0 +1,512 @@
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
+ /* Excluded from this release type: MockPluginProvider */
283
+
284
+ /**
285
+ * Mock implementation of the {@link core-plugin-api#StorageApi} to be used in tests
286
+ * @public
287
+ */
288
+ export declare class MockStorageApi implements StorageApi {
289
+ private readonly namespace;
290
+ private readonly data;
291
+ private readonly bucketStorageApis;
292
+ private constructor();
293
+ static create(data?: MockStorageBucket): MockStorageApi;
294
+ forBucket(name: string): StorageApi;
295
+ snapshot<T extends JsonValue>(key: string): StorageValueSnapshot<T>;
296
+ set<T>(key: string, data: T): Promise<void>;
297
+ remove(key: string): Promise<void>;
298
+ observe$<T>(key: string): Observable<StorageValueSnapshot<T>>;
299
+ private getKeyName;
300
+ private notifyChanges;
301
+ private subscribers;
302
+ private readonly observable;
303
+ }
304
+
305
+ /**
306
+ * Type for map holding data in {@link MockStorageApi}
307
+ * @public
308
+ */
309
+ export declare type MockStorageBucket = {
310
+ [key: string]: any;
311
+ };
312
+
313
+ /**
314
+ * Renders a component inside a Backstage test app, providing a mocked theme
315
+ * and app context, along with mocked APIs.
316
+ *
317
+ * The render executes async effects similar to `renderWithEffects`. To avoid this
318
+ * behavior, use a regular `render()` + `wrapInTestApp()` instead.
319
+ *
320
+ * @param Component - A component or react node to render inside the test app.
321
+ * @param options - Additional options for the rendering.
322
+ * @public
323
+ */
324
+ export declare function renderInTestApp(Component: ComponentType | ReactNode, options?: TestAppOptions): Promise<RenderResult>;
325
+
326
+ /**
327
+ * @public
328
+ * Simplifies rendering of async components in by taking care of the wrapping inside act
329
+ *
330
+ * @remarks
331
+ *
332
+ * Components using useEffect to perform an asynchronous action (such as fetch) must be rendered within an async
333
+ * act call to properly get the final state, even with mocked responses. This utility method makes the signature a bit
334
+ * cleaner, since act doesn't return the result of the evaluated function.
335
+ * https://github.com/testing-library/react-testing-library/issues/281
336
+ * https://github.com/facebook/react/pull/14853
337
+ */
338
+ export declare function renderWithEffects(nodes: ReactElement, options?: Pick<RenderOptions, 'wrapper'>): Promise<RenderResult>;
339
+
340
+ /**
341
+ * Sets up handlers for request mocking
342
+ * @public
343
+ * @param worker - service worker
344
+ */
345
+ export declare function setupRequestMockHandlers(worker: {
346
+ listen: (t: any) => void;
347
+ close: () => void;
348
+ resetHandlers: () => void;
349
+ }): void;
350
+
351
+ /**
352
+ * SyncLogCollector type used in {@link (withLogCollector:2)} callback function.
353
+ * @public
354
+ */
355
+ export declare type SyncLogCollector = () => void;
356
+
357
+ /**
358
+ * The `TestApiProvider` is a Utility API context provider that is particularly
359
+ * well suited for development and test environments such as unit tests, storybooks,
360
+ * and isolated plugin development setups.
361
+ *
362
+ * It lets you provide any number of API implementations, without necessarily
363
+ * having to fully implement each of the APIs.
364
+ *
365
+ * A migration from `ApiRegistry` and `ApiProvider` might look like this, from:
366
+ *
367
+ * ```tsx
368
+ * renderInTestApp(
369
+ * <ApiProvider
370
+ * apis={ApiRegistry.from([
371
+ * [identityApiRef, mockIdentityApi as unknown as IdentityApi]
372
+ * ])}
373
+ * >
374
+ * {...}
375
+ * </ApiProvider>
376
+ * )
377
+ * ```
378
+ *
379
+ * To the following:
380
+ *
381
+ * ```tsx
382
+ * renderInTestApp(
383
+ * <TestApiProvider apis={[[identityApiRef, mockIdentityApi]]}>
384
+ * {...}
385
+ * </TestApiProvider>
386
+ * )
387
+ * ```
388
+ *
389
+ * Note that the cast to `IdentityApi` is no longer needed as long as the mock API
390
+ * implements a subset of the `IdentityApi`.
391
+ *
392
+ * @public
393
+ **/
394
+ export declare const TestApiProvider: <T extends any[]>(props: TestApiProviderProps<T>) => JSX.Element;
395
+
396
+ /**
397
+ * Properties for the {@link TestApiProvider} component.
398
+ *
399
+ * @public
400
+ */
401
+ export declare type TestApiProviderProps<TApiPairs extends any[]> = {
402
+ apis: readonly [...TestApiProviderPropsApiPairs<TApiPairs>];
403
+ children: ReactNode;
404
+ };
405
+
406
+ /** @ignore */
407
+ declare type TestApiProviderPropsApiPair<TApi> = TApi extends infer TImpl ? readonly [ApiRef<TApi>, Partial<TImpl>] : never;
408
+
409
+ /** @ignore */
410
+ declare type TestApiProviderPropsApiPairs<TApiPairs> = {
411
+ [TIndex in keyof TApiPairs]: TestApiProviderPropsApiPair<TApiPairs[TIndex]>;
412
+ };
413
+
414
+ /**
415
+ * The `TestApiRegistry` is an {@link @backstage/core-plugin-api#ApiHolder} implementation
416
+ * that is particularly well suited for development and test environments such as
417
+ * unit tests, storybooks, and isolated plugin development setups.
418
+ *
419
+ * @public
420
+ */
421
+ export declare class TestApiRegistry implements ApiHolder {
422
+ private readonly apis;
423
+ /**
424
+ * Creates a new {@link TestApiRegistry} with a list of API implementation pairs.
425
+ *
426
+ * Similar to the {@link TestApiProvider}, there is no need to provide a full
427
+ * implementation of each API, it's enough to implement the methods that are tested.
428
+ *
429
+ * @example
430
+ * ```ts
431
+ * const apis = TestApiRegistry.from(
432
+ * [configApiRef, new ConfigReader({})],
433
+ * [identityApiRef, { getUserId: () => 'tester' }],
434
+ * );
435
+ * ```
436
+ *
437
+ * @public
438
+ * @param apis - A list of pairs mapping an ApiRef to its respective implementation.
439
+ */
440
+ static from<TApiPairs extends any[]>(...apis: readonly [...TestApiProviderPropsApiPairs<TApiPairs>]): TestApiRegistry;
441
+ private constructor();
442
+ /**
443
+ * Returns an implementation of the API.
444
+ *
445
+ * @public
446
+ */
447
+ get<T>(api: ApiRef<T>): T | undefined;
448
+ }
449
+
450
+ /**
451
+ * Options to customize the behavior of the test app wrapper.
452
+ * @public
453
+ */
454
+ export declare type TestAppOptions = {
455
+ /**
456
+ * Initial route entries to pass along as `initialEntries` to the router.
457
+ */
458
+ routeEntries?: string[];
459
+ /**
460
+ * An object of paths to mount route ref on, with the key being the path and the value
461
+ * being the RouteRef that the path will be bound to. This allows the route refs to be
462
+ * used by `useRouteRef` in the rendered elements.
463
+ *
464
+ * @example
465
+ * wrapInTestApp(<MyComponent />, \{
466
+ * mountedRoutes: \{
467
+ * '/my-path': myRouteRef,
468
+ * \}
469
+ * \})
470
+ * // ...
471
+ * const link = useRouteRef(myRouteRef)
472
+ */
473
+ mountedRoutes?: {
474
+ [path: string]: RouteRef | ExternalRouteRef;
475
+ };
476
+ };
477
+
478
+ /**
479
+ * Asynchronous log collector with that collects all categories
480
+ * @public
481
+ */
482
+ export declare function withLogCollector(callback: AsyncLogCollector): Promise<CollectedLogs<LogFuncs>>;
483
+
484
+ /**
485
+ * Synchronous log collector with that collects all categories
486
+ * @public
487
+ */
488
+ export declare function withLogCollector(callback: SyncLogCollector): CollectedLogs<LogFuncs>;
489
+
490
+ /**
491
+ * Asynchronous log collector with that only collects selected categories
492
+ * @public
493
+ */
494
+ export declare function withLogCollector<T extends LogFuncs>(logsToCollect: T[], callback: AsyncLogCollector): Promise<CollectedLogs<T>>;
495
+
496
+ /**
497
+ * Synchronous log collector with that only collects selected categories
498
+ * @public
499
+ */
500
+ export declare function withLogCollector<T extends LogFuncs>(logsToCollect: T[], callback: SyncLogCollector): CollectedLogs<T>;
501
+
502
+ /**
503
+ * Wraps a component inside a Backstage test app, providing a mocked theme
504
+ * and app context, along with mocked APIs.
505
+ *
506
+ * @param Component - A component or react node to render inside the test app.
507
+ * @param options - Additional options for the rendering.
508
+ * @public
509
+ */
510
+ export declare function wrapInTestApp(Component: ComponentType | ReactNode, options?: TestAppOptions): ReactElement;
511
+
512
+ export { }