@backstage/test-utils 1.2.3-next.0 → 1.2.3-next.2

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