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