@backstage/test-utils 1.7.1-next.0 → 1.7.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 +13 -0
- package/dist/core-plugin-api/src/translation/TranslationRef.esm.js.map +1 -1
- package/dist/deprecated.esm.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/testUtils/TestApiProvider.esm.js.map +1 -1
- package/dist/testUtils/apis/AnalyticsApi/MockAnalyticsApi.esm.js.map +1 -1
- package/dist/testUtils/apis/ConfigApi/MockConfigApi.esm.js.map +1 -1
- package/dist/testUtils/apis/ErrorApi/MockErrorApi.esm.js.map +1 -1
- package/dist/testUtils/apis/FetchApi/MockFetchApi.esm.js.map +1 -1
- package/dist/testUtils/apis/PermissionApi/MockPermissionApi.esm.js.map +1 -1
- package/dist/testUtils/apis/StorageApi/MockStorageApi.esm.js.map +1 -1
- package/dist/testUtils/apis/TranslationApi/MockTranslationApi.esm.js.map +1 -1
- package/dist/testUtils/apis/mockApis.esm.js.map +1 -1
- package/dist/testUtils/appWrappers.esm.js.map +1 -1
- package/dist/testUtils/defaultApis.esm.js +1 -1
- package/dist/testUtils/defaultApis.esm.js.map +1 -1
- package/dist/testUtils/logCollector.esm.js.map +1 -1
- package/dist/testUtils/mockApis.esm.js.map +1 -1
- package/dist/testUtils/mockBreakpoint.esm.js.map +1 -1
- package/dist/testUtils/msw/registerMswTestHooks.esm.js.map +1 -1
- package/dist/testUtils/testingLibrary.esm.js.map +1 -1
- package/package.json +20 -11
- package/alpha/package.json +0 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# @backstage/test-utils
|
|
2
2
|
|
|
3
|
+
## 1.7.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies
|
|
8
|
+
- @backstage/config@1.3.0
|
|
9
|
+
- @backstage/theme@0.6.1
|
|
10
|
+
- @backstage/types@1.2.0
|
|
11
|
+
- @backstage/core-app-api@1.15.2
|
|
12
|
+
- @backstage/plugin-permission-common@0.8.2
|
|
13
|
+
- @backstage/core-plugin-api@1.10.1
|
|
14
|
+
- @backstage/plugin-permission-react@0.4.28
|
|
15
|
+
|
|
3
16
|
## 1.7.1-next.0
|
|
4
17
|
|
|
5
18
|
### Patch Changes
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TranslationRef.esm.js","sources":["../../../../../core-plugin-api/src/translation/TranslationRef.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createTranslationResource,\n TranslationResource,\n} from './TranslationResource';\n\n/** @alpha */\nexport interface TranslationRef<\n TId extends string = string,\n TMessages extends { [key in string]: string } = { [key in string]: string },\n> {\n $$type: '@backstage/TranslationRef';\n\n id: TId;\n\n T: TMessages;\n}\n\n/** @internal */\ntype AnyMessages = { [key in string]: string };\n\n/** @ignore */\ntype AnyNestedMessages = { [key in string]: AnyNestedMessages | string };\n\n/**\n * Flattens a nested message declaration into a flat object with dot-separated keys.\n *\n * @ignore\n */\ntype FlattenedMessages<TMessages extends AnyNestedMessages> =\n // Flatten out object keys into a union structure of objects, e.g. { a: 'a', b: 'b' } -> { a: 'a' } | { b: 'b' }\n // Any nested object will be flattened into the individual unions, e.g. { a: 'a', b: { x: 'x', y: 'y' } } -> { a: 'a' } | { 'b.x': 'x', 'b.y': 'y' }\n // We create this structure by first nesting the desired union types into the original object, and\n // then extract them by indexing with `keyof TMessages` to form the union.\n // Throughout this the objects are wrapped up in a function parameter, which allows us to have the\n // final step of flipping this unions around to an intersection by inferring the function parameter.\n {\n [TKey in keyof TMessages]: (\n _: TMessages[TKey] extends infer TValue // \"local variable\" for the value\n ? TValue extends AnyNestedMessages\n ? FlattenedMessages<TValue> extends infer TNested // Recurse into nested messages, \"local variable\" for the result\n ? {\n [TNestedKey in keyof TNested as `${TKey & string}.${TNestedKey &\n string}`]: TNested[TNestedKey];\n }\n : never\n : { [_ in TKey]: TValue } // Primitive object values are passed through with the same key\n : never,\n ) => void;\n // The `[keyof TMessages]` extracts the object values union from our flattened structure, still wrapped up in function parameters.\n // The `extends (_: infer TIntersection) => void` flips the union to an intersection, at which point we have the correct type.\n }[keyof TMessages] extends (_: infer TIntersection) => void\n ? // This object mapping just expands similar to the Expand<> utility type, providing nicer type hints\n {\n readonly [TExpandKey in keyof TIntersection]: TIntersection[TExpandKey];\n }\n : never;\n\n/** @internal */\nexport interface InternalTranslationRef<\n TId extends string = string,\n TMessages extends { [key in string]: string } = { [key in string]: string },\n> extends TranslationRef<TId, TMessages> {\n version: 'v1';\n\n getDefaultMessages(): AnyMessages;\n\n getDefaultResource(): TranslationResource | undefined;\n}\n\n/** @alpha */\nexport interface TranslationRefOptions<\n TId extends string,\n TNestedMessages extends AnyNestedMessages,\n TTranslations extends {\n [language in string]: () => Promise<{\n default: {\n [key in keyof FlattenedMessages<TNestedMessages>]: string | null;\n };\n }>;\n },\n> {\n id: TId;\n messages: TNestedMessages;\n translations?: TTranslations;\n}\n\nfunction flattenMessages(nested: AnyNestedMessages): AnyMessages {\n const entries = new Array<[string, string]>();\n\n function visit(obj: AnyNestedMessages, prefix: string): void {\n for (const [key, value] of Object.entries(obj)) {\n if (typeof value === 'string') {\n entries.push([prefix + key, value]);\n } else {\n visit(value, `${prefix}${key}.`);\n }\n }\n }\n\n visit(nested, '');\n\n return Object.fromEntries(entries);\n}\n\n/** @internal */\nclass TranslationRefImpl<\n TId extends string,\n TNestedMessages extends AnyNestedMessages,\n> implements InternalTranslationRef<TId, FlattenedMessages<TNestedMessages>>\n{\n #id: TId;\n #messages: FlattenedMessages<TNestedMessages>;\n #resources: TranslationResource | undefined;\n\n constructor(options: TranslationRefOptions<TId, TNestedMessages, any>) {\n this.#id = options.id;\n this.#messages = flattenMessages(\n options.messages,\n ) as FlattenedMessages<TNestedMessages>;\n }\n\n $$type = '@backstage/TranslationRef' as const;\n\n version = 'v1' as const;\n\n get id(): TId {\n return this.#id;\n }\n\n get T(): never {\n throw new Error('Not implemented');\n }\n\n getDefaultMessages(): AnyMessages {\n return this.#messages;\n }\n\n setDefaultResource(resources: TranslationResource): void {\n this.#resources = resources;\n }\n\n getDefaultResource(): TranslationResource | undefined {\n return this.#resources;\n }\n\n toString() {\n return `TranslationRef{id=${this.id}}`;\n }\n}\n\n/** @alpha */\nexport function createTranslationRef<\n TId extends string,\n const TNestedMessages extends AnyNestedMessages,\n TTranslations extends {\n [language in string]: () => Promise<{\n default: {\n [key in keyof FlattenedMessages<TNestedMessages>]: string | null;\n };\n }>;\n },\n>(\n config: TranslationRefOptions<TId, TNestedMessages, TTranslations>,\n): TranslationRef<TId, FlattenedMessages<TNestedMessages>> {\n const ref = new TranslationRefImpl(config);\n if (config.translations) {\n ref.setDefaultResource(\n createTranslationResource({\n ref,\n translations: config.translations as any,\n }),\n );\n }\n return ref;\n}\n\n/** @internal */\nexport function toInternalTranslationRef<\n TId extends string,\n TMessages extends AnyMessages,\n>(ref: TranslationRef<TId, TMessages>): InternalTranslationRef<TId, TMessages> {\n const r = ref as InternalTranslationRef<TId, TMessages>;\n if (r.$$type !== '@backstage/TranslationRef') {\n throw new Error(`Invalid translation ref, bad type '${r.$$type}'`);\n }\n if (r.version !== 'v1') {\n throw new Error(`Invalid translation ref, bad version '${r.version}'`);\n }\n return r;\n}\n"],"names":[],"mappings":"AAiMO,SAAS,yBAGd,GAA6E,EAAA;AAC7E,EAAA,MAAM,CAAI,GAAA,GAAA
|
|
1
|
+
{"version":3,"file":"TranslationRef.esm.js","sources":["../../../../../core-plugin-api/src/translation/TranslationRef.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createTranslationResource,\n TranslationResource,\n} from './TranslationResource';\n\n/** @alpha */\nexport interface TranslationRef<\n TId extends string = string,\n TMessages extends { [key in string]: string } = { [key in string]: string },\n> {\n $$type: '@backstage/TranslationRef';\n\n id: TId;\n\n T: TMessages;\n}\n\n/** @internal */\ntype AnyMessages = { [key in string]: string };\n\n/** @ignore */\ntype AnyNestedMessages = { [key in string]: AnyNestedMessages | string };\n\n/**\n * Flattens a nested message declaration into a flat object with dot-separated keys.\n *\n * @ignore\n */\ntype FlattenedMessages<TMessages extends AnyNestedMessages> =\n // Flatten out object keys into a union structure of objects, e.g. { a: 'a', b: 'b' } -> { a: 'a' } | { b: 'b' }\n // Any nested object will be flattened into the individual unions, e.g. { a: 'a', b: { x: 'x', y: 'y' } } -> { a: 'a' } | { 'b.x': 'x', 'b.y': 'y' }\n // We create this structure by first nesting the desired union types into the original object, and\n // then extract them by indexing with `keyof TMessages` to form the union.\n // Throughout this the objects are wrapped up in a function parameter, which allows us to have the\n // final step of flipping this unions around to an intersection by inferring the function parameter.\n {\n [TKey in keyof TMessages]: (\n _: TMessages[TKey] extends infer TValue // \"local variable\" for the value\n ? TValue extends AnyNestedMessages\n ? FlattenedMessages<TValue> extends infer TNested // Recurse into nested messages, \"local variable\" for the result\n ? {\n [TNestedKey in keyof TNested as `${TKey & string}.${TNestedKey &\n string}`]: TNested[TNestedKey];\n }\n : never\n : { [_ in TKey]: TValue } // Primitive object values are passed through with the same key\n : never,\n ) => void;\n // The `[keyof TMessages]` extracts the object values union from our flattened structure, still wrapped up in function parameters.\n // The `extends (_: infer TIntersection) => void` flips the union to an intersection, at which point we have the correct type.\n }[keyof TMessages] extends (_: infer TIntersection) => void\n ? // This object mapping just expands similar to the Expand<> utility type, providing nicer type hints\n {\n readonly [TExpandKey in keyof TIntersection]: TIntersection[TExpandKey];\n }\n : never;\n\n/** @internal */\nexport interface InternalTranslationRef<\n TId extends string = string,\n TMessages extends { [key in string]: string } = { [key in string]: string },\n> extends TranslationRef<TId, TMessages> {\n version: 'v1';\n\n getDefaultMessages(): AnyMessages;\n\n getDefaultResource(): TranslationResource | undefined;\n}\n\n/** @alpha */\nexport interface TranslationRefOptions<\n TId extends string,\n TNestedMessages extends AnyNestedMessages,\n TTranslations extends {\n [language in string]: () => Promise<{\n default: {\n [key in keyof FlattenedMessages<TNestedMessages>]: string | null;\n };\n }>;\n },\n> {\n id: TId;\n messages: TNestedMessages;\n translations?: TTranslations;\n}\n\nfunction flattenMessages(nested: AnyNestedMessages): AnyMessages {\n const entries = new Array<[string, string]>();\n\n function visit(obj: AnyNestedMessages, prefix: string): void {\n for (const [key, value] of Object.entries(obj)) {\n if (typeof value === 'string') {\n entries.push([prefix + key, value]);\n } else {\n visit(value, `${prefix}${key}.`);\n }\n }\n }\n\n visit(nested, '');\n\n return Object.fromEntries(entries);\n}\n\n/** @internal */\nclass TranslationRefImpl<\n TId extends string,\n TNestedMessages extends AnyNestedMessages,\n> implements InternalTranslationRef<TId, FlattenedMessages<TNestedMessages>>\n{\n #id: TId;\n #messages: FlattenedMessages<TNestedMessages>;\n #resources: TranslationResource | undefined;\n\n constructor(options: TranslationRefOptions<TId, TNestedMessages, any>) {\n this.#id = options.id;\n this.#messages = flattenMessages(\n options.messages,\n ) as FlattenedMessages<TNestedMessages>;\n }\n\n $$type = '@backstage/TranslationRef' as const;\n\n version = 'v1' as const;\n\n get id(): TId {\n return this.#id;\n }\n\n get T(): never {\n throw new Error('Not implemented');\n }\n\n getDefaultMessages(): AnyMessages {\n return this.#messages;\n }\n\n setDefaultResource(resources: TranslationResource): void {\n this.#resources = resources;\n }\n\n getDefaultResource(): TranslationResource | undefined {\n return this.#resources;\n }\n\n toString() {\n return `TranslationRef{id=${this.id}}`;\n }\n}\n\n/** @alpha */\nexport function createTranslationRef<\n TId extends string,\n const TNestedMessages extends AnyNestedMessages,\n TTranslations extends {\n [language in string]: () => Promise<{\n default: {\n [key in keyof FlattenedMessages<TNestedMessages>]: string | null;\n };\n }>;\n },\n>(\n config: TranslationRefOptions<TId, TNestedMessages, TTranslations>,\n): TranslationRef<TId, FlattenedMessages<TNestedMessages>> {\n const ref = new TranslationRefImpl(config);\n if (config.translations) {\n ref.setDefaultResource(\n createTranslationResource({\n ref,\n translations: config.translations as any,\n }),\n );\n }\n return ref;\n}\n\n/** @internal */\nexport function toInternalTranslationRef<\n TId extends string,\n TMessages extends AnyMessages,\n>(ref: TranslationRef<TId, TMessages>): InternalTranslationRef<TId, TMessages> {\n const r = ref as InternalTranslationRef<TId, TMessages>;\n if (r.$$type !== '@backstage/TranslationRef') {\n throw new Error(`Invalid translation ref, bad type '${r.$$type}'`);\n }\n if (r.version !== 'v1') {\n throw new Error(`Invalid translation ref, bad version '${r.version}'`);\n }\n return r;\n}\n"],"names":[],"mappings":"AAiMO,SAAS,yBAGd,GAA6E,EAAA;AAC7E,EAAA,MAAM,CAAI,GAAA,GAAA;AACV,EAAI,IAAA,CAAA,CAAE,WAAW,2BAA6B,EAAA;AAC5C,IAAA,MAAM,IAAI,KAAA,CAAM,CAAsC,mCAAA,EAAA,CAAA,CAAE,MAAM,CAAG,CAAA,CAAA,CAAA;AAAA;AAEnE,EAAI,IAAA,CAAA,CAAE,YAAY,IAAM,EAAA;AACtB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAyC,sCAAA,EAAA,CAAA,CAAE,OAAO,CAAG,CAAA,CAAA,CAAA;AAAA;AAEvE,EAAO,OAAA,CAAA;AACT;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"deprecated.esm.js","sources":["../src/deprecated.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerMswTestHooks } from './testUtils/msw';\n\n/**\n * @public\n * @deprecated Use `registerMswTestHooks` from `@backstage/test-utils` instead.\n */\nexport function setupRequestMockHandlers(worker: {\n listen: (t: any) => void;\n close: () => void;\n resetHandlers: () => void;\n}): void {\n registerMswTestHooks(worker);\n}\n"],"names":[],"mappings":";;AAsBO,SAAS,yBAAyB,MAIhC,EAAA;AACP,EAAA,oBAAA,CAAqB,MAAM,CAAA
|
|
1
|
+
{"version":3,"file":"deprecated.esm.js","sources":["../src/deprecated.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerMswTestHooks } from './testUtils/msw';\n\n/**\n * @public\n * @deprecated Use `registerMswTestHooks` from `@backstage/test-utils` instead.\n */\nexport function setupRequestMockHandlers(worker: {\n listen: (t: any) => void;\n close: () => void;\n resetHandlers: () => void;\n}): void {\n registerMswTestHooks(worker);\n}\n"],"names":[],"mappings":";;AAsBO,SAAS,yBAAyB,MAIhC,EAAA;AACP,EAAA,oBAAA,CAAqB,MAAM,CAAA;AAC7B;;;;"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/// <reference types="jest" />
|
|
2
|
-
import { AnalyticsApi, AnalyticsEvent, ConfigApi, ErrorApiError, ErrorApiErrorContext,
|
|
2
|
+
import { AnalyticsApi, AnalyticsEvent, ConfigApi, ErrorApi, ErrorApiError, ErrorApiErrorContext, FetchApi, DiscoveryApi, IdentityApi, StorageApi, StorageValueSnapshot, ApiFactory, RouteRef, ExternalRouteRef, AppComponents, IconComponent, ApiRef, ApiHolder } from '@backstage/core-plugin-api';
|
|
3
3
|
import * as _backstage_config from '@backstage/config';
|
|
4
4
|
import { Config } from '@backstage/config';
|
|
5
5
|
import { JsonObject, JsonValue, Observable } from '@backstage/types';
|
|
@@ -7,7 +7,7 @@ import crossFetch from 'cross-fetch';
|
|
|
7
7
|
import { PermissionApi } from '@backstage/plugin-permission-react';
|
|
8
8
|
import { EvaluatePermissionRequest, AuthorizeResult, EvaluatePermissionResponse } from '@backstage/plugin-permission-common';
|
|
9
9
|
import { TranslationApi } from '@backstage/core-plugin-api/alpha';
|
|
10
|
-
import React, { ReactElement,
|
|
10
|
+
import React, { ReactElement, ComponentType, ReactNode, PropsWithChildren } from 'react';
|
|
11
11
|
import { AppIcons } from '@backstage/core-app-api';
|
|
12
12
|
import { RenderOptions, RenderResult, MatcherFunction } from '@testing-library/react';
|
|
13
13
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TestApiProvider.esm.js","sources":["../../src/testUtils/TestApiProvider.tsx"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport React, { ReactNode } from 'react';\nimport { ApiProvider } from '@backstage/core-app-api';\nimport { ApiRef, ApiHolder } from '@backstage/core-plugin-api';\n\n/** @ignore */\ntype TestApiProviderPropsApiPair<TApi> = TApi extends infer TImpl\n ? readonly [ApiRef<TApi>, Partial<TImpl>]\n : never;\n\n/** @ignore */\ntype TestApiProviderPropsApiPairs<TApiPairs> = {\n [TIndex in keyof TApiPairs]: TestApiProviderPropsApiPair<TApiPairs[TIndex]>;\n};\n\n/**\n * Properties for the {@link TestApiProvider} component.\n *\n * @public\n */\nexport type TestApiProviderProps<TApiPairs extends any[]> = {\n apis: readonly [...TestApiProviderPropsApiPairs<TApiPairs>];\n children: ReactNode;\n};\n\n/**\n * The `TestApiRegistry` is an {@link @backstage/core-plugin-api#ApiHolder} implementation\n * that is particularly well suited for development and test environments such as\n * unit tests, storybooks, and isolated plugin development setups.\n *\n * @public\n */\nexport class TestApiRegistry implements ApiHolder {\n /**\n * Creates a new {@link TestApiRegistry} with a list of API implementation pairs.\n *\n * Similar to the {@link TestApiProvider}, there is no need to provide a full\n * implementation of each API, it's enough to implement the methods that are tested.\n *\n * @example\n * ```ts\n * const apis = TestApiRegistry.from(\n * [configApiRef, new ConfigReader({})],\n * [identityApiRef, { getUserId: () => 'tester' }],\n * );\n * ```\n *\n * @public\n * @param apis - A list of pairs mapping an ApiRef to its respective implementation.\n */\n static from<TApiPairs extends any[]>(\n ...apis: readonly [...TestApiProviderPropsApiPairs<TApiPairs>]\n ) {\n return new TestApiRegistry(\n new Map(apis.map(([api, impl]) => [api.id, impl])),\n );\n }\n\n private constructor(private readonly apis: Map<string, unknown>) {}\n\n /**\n * Returns an implementation of the API.\n *\n * @public\n */\n get<T>(api: ApiRef<T>): T | undefined {\n return this.apis.get(api.id) as T | undefined;\n }\n}\n\n/**\n * The `TestApiProvider` is a Utility API context provider that is particularly\n * well suited for development and test environments such as unit tests, storybooks,\n * and isolated plugin development setups.\n *\n * It lets you provide any number of API implementations, without necessarily\n * having to fully implement each of the APIs.\n *\n * @remarks\n * todo: remove this remark tag and ship in the api-reference. There's some odd formatting going on when this is made into a markdown doc, that there's no line break between\n * the emitted <p> for To the following </p> so what happens is that when parsing in docusaurus, it thinks that the code block is mdx rather than a code\n * snippet. Just omitting this from the report for now until we can work out how to fix later.\n * A migration from `ApiRegistry` and `ApiProvider` might look like this, from:\n *\n * ```tsx\n * renderInTestApp(\n * <ApiProvider\n * apis={ApiRegistry.from([\n * [identityApiRef, mockIdentityApi as unknown as IdentityApi]\n * ])}\n * >\n * ...\n * </ApiProvider>\n * )\n * ```\n *\n * To the following:\n *\n * ```tsx\n * renderInTestApp(\n * <TestApiProvider apis={[[identityApiRef, mockIdentityApi]]}>\n * ...\n * </TestApiProvider>\n * )\n * ```\n *\n * Note that the cast to `IdentityApi` is no longer needed as long as the mock API\n * implements a subset of the `IdentityApi`.\n *\n * @public\n */\nexport const TestApiProvider = <T extends any[]>(\n props: TestApiProviderProps<T>,\n) => {\n return (\n <ApiProvider\n apis={TestApiRegistry.from(...props.apis)}\n children={props.children}\n />\n );\n};\n"],"names":[],"mappings":";;;AA+CO,MAAM,eAAqC,CAAA;AAAA,EA0BxC,YAA6B,IAA4B,EAAA;AAA5B,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA
|
|
1
|
+
{"version":3,"file":"TestApiProvider.esm.js","sources":["../../src/testUtils/TestApiProvider.tsx"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport React, { ReactNode } from 'react';\nimport { ApiProvider } from '@backstage/core-app-api';\nimport { ApiRef, ApiHolder } from '@backstage/core-plugin-api';\n\n/** @ignore */\ntype TestApiProviderPropsApiPair<TApi> = TApi extends infer TImpl\n ? readonly [ApiRef<TApi>, Partial<TImpl>]\n : never;\n\n/** @ignore */\ntype TestApiProviderPropsApiPairs<TApiPairs> = {\n [TIndex in keyof TApiPairs]: TestApiProviderPropsApiPair<TApiPairs[TIndex]>;\n};\n\n/**\n * Properties for the {@link TestApiProvider} component.\n *\n * @public\n */\nexport type TestApiProviderProps<TApiPairs extends any[]> = {\n apis: readonly [...TestApiProviderPropsApiPairs<TApiPairs>];\n children: ReactNode;\n};\n\n/**\n * The `TestApiRegistry` is an {@link @backstage/core-plugin-api#ApiHolder} implementation\n * that is particularly well suited for development and test environments such as\n * unit tests, storybooks, and isolated plugin development setups.\n *\n * @public\n */\nexport class TestApiRegistry implements ApiHolder {\n /**\n * Creates a new {@link TestApiRegistry} with a list of API implementation pairs.\n *\n * Similar to the {@link TestApiProvider}, there is no need to provide a full\n * implementation of each API, it's enough to implement the methods that are tested.\n *\n * @example\n * ```ts\n * const apis = TestApiRegistry.from(\n * [configApiRef, new ConfigReader({})],\n * [identityApiRef, { getUserId: () => 'tester' }],\n * );\n * ```\n *\n * @public\n * @param apis - A list of pairs mapping an ApiRef to its respective implementation.\n */\n static from<TApiPairs extends any[]>(\n ...apis: readonly [...TestApiProviderPropsApiPairs<TApiPairs>]\n ) {\n return new TestApiRegistry(\n new Map(apis.map(([api, impl]) => [api.id, impl])),\n );\n }\n\n private constructor(private readonly apis: Map<string, unknown>) {}\n\n /**\n * Returns an implementation of the API.\n *\n * @public\n */\n get<T>(api: ApiRef<T>): T | undefined {\n return this.apis.get(api.id) as T | undefined;\n }\n}\n\n/**\n * The `TestApiProvider` is a Utility API context provider that is particularly\n * well suited for development and test environments such as unit tests, storybooks,\n * and isolated plugin development setups.\n *\n * It lets you provide any number of API implementations, without necessarily\n * having to fully implement each of the APIs.\n *\n * @remarks\n * todo: remove this remark tag and ship in the api-reference. There's some odd formatting going on when this is made into a markdown doc, that there's no line break between\n * the emitted <p> for To the following </p> so what happens is that when parsing in docusaurus, it thinks that the code block is mdx rather than a code\n * snippet. Just omitting this from the report for now until we can work out how to fix later.\n * A migration from `ApiRegistry` and `ApiProvider` might look like this, from:\n *\n * ```tsx\n * renderInTestApp(\n * <ApiProvider\n * apis={ApiRegistry.from([\n * [identityApiRef, mockIdentityApi as unknown as IdentityApi]\n * ])}\n * >\n * ...\n * </ApiProvider>\n * )\n * ```\n *\n * To the following:\n *\n * ```tsx\n * renderInTestApp(\n * <TestApiProvider apis={[[identityApiRef, mockIdentityApi]]}>\n * ...\n * </TestApiProvider>\n * )\n * ```\n *\n * Note that the cast to `IdentityApi` is no longer needed as long as the mock API\n * implements a subset of the `IdentityApi`.\n *\n * @public\n */\nexport const TestApiProvider = <T extends any[]>(\n props: TestApiProviderProps<T>,\n) => {\n return (\n <ApiProvider\n apis={TestApiRegistry.from(...props.apis)}\n children={props.children}\n />\n );\n};\n"],"names":[],"mappings":";;;AA+CO,MAAM,eAAqC,CAAA;AAAA,EA0BxC,YAA6B,IAA4B,EAAA;AAA5B,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAAA;AAA6B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EARlE,OAAO,QACF,IACH,EAAA;AACA,IAAA,OAAO,IAAI,eAAA;AAAA,MACT,IAAI,GAAA,CAAI,IAAK,CAAA,GAAA,CAAI,CAAC,CAAC,GAAA,EAAK,IAAI,CAAA,KAAM,CAAC,GAAA,CAAI,EAAI,EAAA,IAAI,CAAC,CAAC;AAAA,KACnD;AAAA;AACF;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,IAAO,GAA+B,EAAA;AACpC,IAAA,OAAO,IAAK,CAAA,IAAA,CAAK,GAAI,CAAA,GAAA,CAAI,EAAE,CAAA;AAAA;AAE/B;AA2Ca,MAAA,eAAA,GAAkB,CAC7B,KACG,KAAA;AACH,EACE,uBAAA,KAAA,CAAA,aAAA;AAAA,IAAC,WAAA;AAAA,IAAA;AAAA,MACC,IAAM,EAAA,eAAA,CAAgB,IAAK,CAAA,GAAG,MAAM,IAAI,CAAA;AAAA,MACxC,UAAU,KAAM,CAAA;AAAA;AAAA,GAClB;AAEJ;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MockAnalyticsApi.esm.js","sources":["../../../../src/testUtils/apis/AnalyticsApi/MockAnalyticsApi.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AnalyticsApi, AnalyticsEvent } from '@backstage/core-plugin-api';\n\n/**\n * Mock implementation of {@link core-plugin-api#AnalyticsApi} with helpers to ensure that events are sent correctly.\n * Use getEvents in tests to verify captured events.\n *\n * @public\n * @deprecated Use {@link @backstage/test-utils#mockApis.(analytics:namespace)} instead\n */\nexport class MockAnalyticsApi implements AnalyticsApi {\n private events: AnalyticsEvent[] = [];\n\n captureEvent(event: AnalyticsEvent) {\n const { action, subject, value, attributes, context } = event;\n\n this.events.push({\n action,\n subject,\n context,\n ...(value !== undefined ? { value } : {}),\n ...(attributes !== undefined ? { attributes } : {}),\n });\n }\n\n getEvents(): AnalyticsEvent[] {\n return this.events;\n }\n}\n"],"names":[],"mappings":"AAyBO,MAAM,gBAAyC,CAAA;AAAA,EAC5C,SAA2B,EAAC
|
|
1
|
+
{"version":3,"file":"MockAnalyticsApi.esm.js","sources":["../../../../src/testUtils/apis/AnalyticsApi/MockAnalyticsApi.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AnalyticsApi, AnalyticsEvent } from '@backstage/core-plugin-api';\n\n/**\n * Mock implementation of {@link core-plugin-api#AnalyticsApi} with helpers to ensure that events are sent correctly.\n * Use getEvents in tests to verify captured events.\n *\n * @public\n * @deprecated Use {@link @backstage/test-utils#mockApis.(analytics:namespace)} instead\n */\nexport class MockAnalyticsApi implements AnalyticsApi {\n private events: AnalyticsEvent[] = [];\n\n captureEvent(event: AnalyticsEvent) {\n const { action, subject, value, attributes, context } = event;\n\n this.events.push({\n action,\n subject,\n context,\n ...(value !== undefined ? { value } : {}),\n ...(attributes !== undefined ? { attributes } : {}),\n });\n }\n\n getEvents(): AnalyticsEvent[] {\n return this.events;\n }\n}\n"],"names":[],"mappings":"AAyBO,MAAM,gBAAyC,CAAA;AAAA,EAC5C,SAA2B,EAAC;AAAA,EAEpC,aAAa,KAAuB,EAAA;AAClC,IAAA,MAAM,EAAE,MAAQ,EAAA,OAAA,EAAS,KAAO,EAAA,UAAA,EAAY,SAAY,GAAA,KAAA;AAExD,IAAA,IAAA,CAAK,OAAO,IAAK,CAAA;AAAA,MACf,MAAA;AAAA,MACA,OAAA;AAAA,MACA,OAAA;AAAA,MACA,GAAI,KAAU,KAAA,KAAA,CAAA,GAAY,EAAE,KAAA,KAAU,EAAC;AAAA,MACvC,GAAI,UAAe,KAAA,KAAA,CAAA,GAAY,EAAE,UAAA,KAAe;AAAC,KAClD,CAAA;AAAA;AACH,EAEA,SAA8B,GAAA;AAC5B,IAAA,OAAO,IAAK,CAAA,MAAA;AAAA;AAEhB;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MockConfigApi.esm.js","sources":["../../../../src/testUtils/apis/ConfigApi/MockConfigApi.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config, ConfigReader } from '@backstage/config';\nimport { JsonObject, JsonValue } from '@backstage/types';\nimport { ConfigApi } from '@backstage/core-plugin-api';\n\n/**\n * MockConfigApi is a thin wrapper around {@link @backstage/config#ConfigReader}\n * that can be used to mock configuration using a plain object.\n *\n * @public\n * @deprecated Use {@link mockApis.(config:namespace)} instead\n * @example\n * ```tsx\n * const mockConfig = new MockConfigApi({\n * app: { baseUrl: 'https://example.com' },\n * });\n *\n * const rendered = await renderInTestApp(\n * <TestApiProvider apis={[[configApiRef, mockConfig]]}>\n * <MyTestedComponent />\n * </TestApiProvider>,\n * );\n * ```\n */\nexport class MockConfigApi implements ConfigApi {\n private readonly config: ConfigReader;\n\n // NOTE: not extending in order to avoid inheriting the static `.fromConfigs`\n constructor(data: JsonObject) {\n this.config = new ConfigReader(data);\n }\n\n /** {@inheritdoc @backstage/config#Config.has} */\n has(key: string): boolean {\n return this.config.has(key);\n }\n /** {@inheritdoc @backstage/config#Config.keys} */\n keys(): string[] {\n return this.config.keys();\n }\n /** {@inheritdoc @backstage/config#Config.get} */\n get<T = JsonValue>(key?: string): T {\n return this.config.get(key);\n }\n /** {@inheritdoc @backstage/config#Config.getOptional} */\n getOptional<T = JsonValue>(key?: string): T | undefined {\n return this.config.getOptional(key);\n }\n /** {@inheritdoc @backstage/config#Config.getConfig} */\n getConfig(key: string): Config {\n return this.config.getConfig(key);\n }\n /** {@inheritdoc @backstage/config#Config.getOptionalConfig} */\n getOptionalConfig(key: string): Config | undefined {\n return this.config.getOptionalConfig(key);\n }\n /** {@inheritdoc @backstage/config#Config.getConfigArray} */\n getConfigArray(key: string): Config[] {\n return this.config.getConfigArray(key);\n }\n /** {@inheritdoc @backstage/config#Config.getOptionalConfigArray} */\n getOptionalConfigArray(key: string): Config[] | undefined {\n return this.config.getOptionalConfigArray(key);\n }\n /** {@inheritdoc @backstage/config#Config.getNumber} */\n getNumber(key: string): number {\n return this.config.getNumber(key);\n }\n /** {@inheritdoc @backstage/config#Config.getOptionalNumber} */\n getOptionalNumber(key: string): number | undefined {\n return this.config.getOptionalNumber(key);\n }\n /** {@inheritdoc @backstage/config#Config.getBoolean} */\n getBoolean(key: string): boolean {\n return this.config.getBoolean(key);\n }\n /** {@inheritdoc @backstage/config#Config.getOptionalBoolean} */\n getOptionalBoolean(key: string): boolean | undefined {\n return this.config.getOptionalBoolean(key);\n }\n /** {@inheritdoc @backstage/config#Config.getString} */\n getString(key: string): string {\n return this.config.getString(key);\n }\n /** {@inheritdoc @backstage/config#Config.getOptionalString} */\n getOptionalString(key: string): string | undefined {\n return this.config.getOptionalString(key);\n }\n /** {@inheritdoc @backstage/config#Config.getStringArray} */\n getStringArray(key: string): string[] {\n return this.config.getStringArray(key);\n }\n /** {@inheritdoc @backstage/config#Config.getOptionalStringArray} */\n getOptionalStringArray(key: string): string[] | undefined {\n return this.config.getOptionalStringArray(key);\n }\n}\n"],"names":[],"mappings":";;AAuCO,MAAM,aAAmC,CAAA;AAAA,EAC7B,MAAA
|
|
1
|
+
{"version":3,"file":"MockConfigApi.esm.js","sources":["../../../../src/testUtils/apis/ConfigApi/MockConfigApi.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config, ConfigReader } from '@backstage/config';\nimport { JsonObject, JsonValue } from '@backstage/types';\nimport { ConfigApi } from '@backstage/core-plugin-api';\n\n/**\n * MockConfigApi is a thin wrapper around {@link @backstage/config#ConfigReader}\n * that can be used to mock configuration using a plain object.\n *\n * @public\n * @deprecated Use {@link mockApis.(config:namespace)} instead\n * @example\n * ```tsx\n * const mockConfig = new MockConfigApi({\n * app: { baseUrl: 'https://example.com' },\n * });\n *\n * const rendered = await renderInTestApp(\n * <TestApiProvider apis={[[configApiRef, mockConfig]]}>\n * <MyTestedComponent />\n * </TestApiProvider>,\n * );\n * ```\n */\nexport class MockConfigApi implements ConfigApi {\n private readonly config: ConfigReader;\n\n // NOTE: not extending in order to avoid inheriting the static `.fromConfigs`\n constructor(data: JsonObject) {\n this.config = new ConfigReader(data);\n }\n\n /** {@inheritdoc @backstage/config#Config.has} */\n has(key: string): boolean {\n return this.config.has(key);\n }\n /** {@inheritdoc @backstage/config#Config.keys} */\n keys(): string[] {\n return this.config.keys();\n }\n /** {@inheritdoc @backstage/config#Config.get} */\n get<T = JsonValue>(key?: string): T {\n return this.config.get(key);\n }\n /** {@inheritdoc @backstage/config#Config.getOptional} */\n getOptional<T = JsonValue>(key?: string): T | undefined {\n return this.config.getOptional(key);\n }\n /** {@inheritdoc @backstage/config#Config.getConfig} */\n getConfig(key: string): Config {\n return this.config.getConfig(key);\n }\n /** {@inheritdoc @backstage/config#Config.getOptionalConfig} */\n getOptionalConfig(key: string): Config | undefined {\n return this.config.getOptionalConfig(key);\n }\n /** {@inheritdoc @backstage/config#Config.getConfigArray} */\n getConfigArray(key: string): Config[] {\n return this.config.getConfigArray(key);\n }\n /** {@inheritdoc @backstage/config#Config.getOptionalConfigArray} */\n getOptionalConfigArray(key: string): Config[] | undefined {\n return this.config.getOptionalConfigArray(key);\n }\n /** {@inheritdoc @backstage/config#Config.getNumber} */\n getNumber(key: string): number {\n return this.config.getNumber(key);\n }\n /** {@inheritdoc @backstage/config#Config.getOptionalNumber} */\n getOptionalNumber(key: string): number | undefined {\n return this.config.getOptionalNumber(key);\n }\n /** {@inheritdoc @backstage/config#Config.getBoolean} */\n getBoolean(key: string): boolean {\n return this.config.getBoolean(key);\n }\n /** {@inheritdoc @backstage/config#Config.getOptionalBoolean} */\n getOptionalBoolean(key: string): boolean | undefined {\n return this.config.getOptionalBoolean(key);\n }\n /** {@inheritdoc @backstage/config#Config.getString} */\n getString(key: string): string {\n return this.config.getString(key);\n }\n /** {@inheritdoc @backstage/config#Config.getOptionalString} */\n getOptionalString(key: string): string | undefined {\n return this.config.getOptionalString(key);\n }\n /** {@inheritdoc @backstage/config#Config.getStringArray} */\n getStringArray(key: string): string[] {\n return this.config.getStringArray(key);\n }\n /** {@inheritdoc @backstage/config#Config.getOptionalStringArray} */\n getOptionalStringArray(key: string): string[] | undefined {\n return this.config.getOptionalStringArray(key);\n }\n}\n"],"names":[],"mappings":";;AAuCO,MAAM,aAAmC,CAAA;AAAA,EAC7B,MAAA;AAAA;AAAA,EAGjB,YAAY,IAAkB,EAAA;AAC5B,IAAK,IAAA,CAAA,MAAA,GAAS,IAAI,YAAA,CAAa,IAAI,CAAA;AAAA;AACrC;AAAA,EAGA,IAAI,GAAsB,EAAA;AACxB,IAAO,OAAA,IAAA,CAAK,MAAO,CAAA,GAAA,CAAI,GAAG,CAAA;AAAA;AAC5B;AAAA,EAEA,IAAiB,GAAA;AACf,IAAO,OAAA,IAAA,CAAK,OAAO,IAAK,EAAA;AAAA;AAC1B;AAAA,EAEA,IAAmB,GAAiB,EAAA;AAClC,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AACjD,IAAO,OAAA,IAAA,CAAK,MAAO,CAAA,iBAAA,CAAkB,GAAG,CAAA;AAAA;AAC1C;AAAA,EAEA,eAAe,GAAuB,EAAA;AACpC,IAAO,OAAA,IAAA,CAAK,MAAO,CAAA,cAAA,CAAe,GAAG,CAAA;AAAA;AACvC;AAAA,EAEA,uBAAuB,GAAmC,EAAA;AACxD,IAAO,OAAA,IAAA,CAAK,MAAO,CAAA,sBAAA,CAAuB,GAAG,CAAA;AAAA;AAEjD;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MockErrorApi.esm.js","sources":["../../../../src/testUtils/apis/ErrorApi/MockErrorApi.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ErrorApi,\n ErrorApiError,\n ErrorApiErrorContext,\n} from '@backstage/core-plugin-api';\nimport { Observable } from '@backstage/types';\n\n/**\n * Constructor arguments for {@link MockErrorApi}\n * @public\n */\nexport type MockErrorApiOptions = {\n // Need to be true if getErrors is used in testing.\n collect?: boolean;\n};\n\n/**\n * ErrorWithContext contains error and ErrorApiErrorContext\n * @public\n */\nexport type ErrorWithContext = {\n error: ErrorApiError;\n context?: ErrorApiErrorContext;\n};\n\ntype Waiter = {\n pattern: RegExp;\n resolve: (err: ErrorWithContext) => void;\n};\n\nconst nullObservable = {\n subscribe: () => ({ unsubscribe: () => {}, closed: true }),\n\n [Symbol.observable]() {\n return this;\n },\n};\n\n/**\n * Mock implementation of the {@link core-plugin-api#ErrorApi} to be used in tests.\n * Includes withForError and getErrors methods for error testing.\n * @public\n */\nexport class MockErrorApi implements ErrorApi {\n private readonly errors = new Array<ErrorWithContext>();\n private readonly waiters = new Set<Waiter>();\n\n constructor(private readonly options: MockErrorApiOptions = {}) {}\n\n post(error: ErrorApiError, context?: ErrorApiErrorContext) {\n if (this.options.collect) {\n this.errors.push({ error, context });\n\n for (const waiter of this.waiters) {\n if (waiter.pattern.test(error.message)) {\n this.waiters.delete(waiter);\n waiter.resolve({ error, context });\n }\n }\n\n return;\n }\n\n throw new Error(`MockErrorApi received unexpected error, ${error}`);\n }\n\n error$(): Observable<{\n error: ErrorApiError;\n context?: ErrorApiErrorContext;\n }> {\n return nullObservable;\n }\n\n getErrors(): ErrorWithContext[] {\n return this.errors;\n }\n\n waitForError(\n pattern: RegExp,\n timeoutMs: number = 2000,\n ): Promise<ErrorWithContext> {\n return new Promise<ErrorWithContext>((resolve, reject) => {\n setTimeout(() => {\n reject(new Error('Timed out waiting for error'));\n }, timeoutMs);\n\n this.waiters.add({ resolve, pattern });\n });\n }\n}\n"],"names":[],"mappings":"AA8CA,MAAM,cAAiB,GAAA;AAAA,EACrB,SAAW,EAAA,OAAO,EAAE,WAAA,EAAa,MAAM;AAAA,GAAC,EAAG,QAAQ,IAAK,EAAA,CAAA;AAAA,EAExD,CAAC,MAAO,CAAA,UAAU,CAAI,GAAA;AACpB,IAAO,OAAA,IAAA
|
|
1
|
+
{"version":3,"file":"MockErrorApi.esm.js","sources":["../../../../src/testUtils/apis/ErrorApi/MockErrorApi.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ErrorApi,\n ErrorApiError,\n ErrorApiErrorContext,\n} from '@backstage/core-plugin-api';\nimport { Observable } from '@backstage/types';\n\n/**\n * Constructor arguments for {@link MockErrorApi}\n * @public\n */\nexport type MockErrorApiOptions = {\n // Need to be true if getErrors is used in testing.\n collect?: boolean;\n};\n\n/**\n * ErrorWithContext contains error and ErrorApiErrorContext\n * @public\n */\nexport type ErrorWithContext = {\n error: ErrorApiError;\n context?: ErrorApiErrorContext;\n};\n\ntype Waiter = {\n pattern: RegExp;\n resolve: (err: ErrorWithContext) => void;\n};\n\nconst nullObservable = {\n subscribe: () => ({ unsubscribe: () => {}, closed: true }),\n\n [Symbol.observable]() {\n return this;\n },\n};\n\n/**\n * Mock implementation of the {@link core-plugin-api#ErrorApi} to be used in tests.\n * Includes withForError and getErrors methods for error testing.\n * @public\n */\nexport class MockErrorApi implements ErrorApi {\n private readonly errors = new Array<ErrorWithContext>();\n private readonly waiters = new Set<Waiter>();\n\n constructor(private readonly options: MockErrorApiOptions = {}) {}\n\n post(error: ErrorApiError, context?: ErrorApiErrorContext) {\n if (this.options.collect) {\n this.errors.push({ error, context });\n\n for (const waiter of this.waiters) {\n if (waiter.pattern.test(error.message)) {\n this.waiters.delete(waiter);\n waiter.resolve({ error, context });\n }\n }\n\n return;\n }\n\n throw new Error(`MockErrorApi received unexpected error, ${error}`);\n }\n\n error$(): Observable<{\n error: ErrorApiError;\n context?: ErrorApiErrorContext;\n }> {\n return nullObservable;\n }\n\n getErrors(): ErrorWithContext[] {\n return this.errors;\n }\n\n waitForError(\n pattern: RegExp,\n timeoutMs: number = 2000,\n ): Promise<ErrorWithContext> {\n return new Promise<ErrorWithContext>((resolve, reject) => {\n setTimeout(() => {\n reject(new Error('Timed out waiting for error'));\n }, timeoutMs);\n\n this.waiters.add({ resolve, pattern });\n });\n }\n}\n"],"names":[],"mappings":"AA8CA,MAAM,cAAiB,GAAA;AAAA,EACrB,SAAW,EAAA,OAAO,EAAE,WAAA,EAAa,MAAM;AAAA,GAAC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AA,SAC9C,SAAS,CAAA;AAEZ,MAAA,IAAA,CAAK,OAAQ,CAAA,GAAA,CAAI,EAAE,OAAA,EAAS,SAAS,CAAA;AAAA,KACtC,CAAA;AAAA;AAEL;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MockFetchApi.esm.js","sources":["../../../../src/testUtils/apis/FetchApi/MockFetchApi.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createFetchApi,\n FetchMiddleware,\n FetchMiddlewares,\n} from '@backstage/core-app-api';\nimport {\n DiscoveryApi,\n FetchApi,\n IdentityApi,\n} from '@backstage/core-plugin-api';\nimport crossFetch, { Response } from 'cross-fetch';\n\n/**\n * The options given when constructing a {@link MockFetchApi}.\n *\n * @public\n */\nexport interface MockFetchApiOptions {\n /**\n * Define the underlying base `fetch` implementation.\n *\n * @defaultValue undefined\n * @remarks\n *\n * Leaving out this parameter or passing `undefined`, makes the API use the\n * global `fetch` implementation to make real network requests.\n *\n * `'none'` swallows all calls and makes no requests at all.\n *\n * You can also pass in any `fetch` compatible callback, such as a\n * `jest.fn()`, if you want to use a custom implementation or to just track\n * and assert on calls.\n */\n baseImplementation?: undefined | 'none' | typeof crossFetch;\n\n /**\n * Add translation from `plugin://` URLs to concrete http(s) URLs, basically\n * simulating what\n * {@link @backstage/core-app-api#FetchMiddlewares.resolvePluginProtocol}\n * does.\n *\n * @defaultValue undefined\n * @remarks\n *\n * Leaving out this parameter or passing `undefined`, disables plugin protocol\n * translation.\n *\n * To enable the feature, pass in a discovery API which is then used to\n * resolve the URLs.\n */\n resolvePluginProtocol?:\n | undefined\n | { discoveryApi: Pick<DiscoveryApi, 'getBaseUrl'> };\n\n /**\n * Add token based Authorization headers to requests, basically simulating\n * what {@link @backstage/core-app-api#FetchMiddlewares.injectIdentityAuth}\n * does.\n *\n * @defaultValue undefined\n * @remarks\n *\n * Leaving out this parameter or passing `undefined`, disables auth injection.\n *\n * To enable the feature, pass in either a static token or an identity API\n * which is queried on each request for a token.\n */\n injectIdentityAuth?:\n | undefined\n | { token: string }\n | { identityApi: Pick<IdentityApi, 'getCredentials'> };\n}\n\n/**\n * A test helper implementation of {@link @backstage/core-plugin-api#FetchApi}.\n *\n * @public\n */\nexport class MockFetchApi implements FetchApi {\n private readonly implementation: FetchApi;\n\n /**\n * Creates a mock {@link @backstage/core-plugin-api#FetchApi}.\n */\n constructor(options?: MockFetchApiOptions) {\n this.implementation = build(options);\n }\n\n /** {@inheritdoc @backstage/core-plugin-api#FetchApi.fetch} */\n get fetch(): typeof crossFetch {\n return this.implementation.fetch;\n }\n}\n\n//\n// Helpers\n//\n\nfunction build(options?: MockFetchApiOptions): FetchApi {\n return createFetchApi({\n baseImplementation: baseImplementation(options),\n middleware: [\n resolvePluginProtocol(options),\n injectIdentityAuth(options),\n ].filter((x): x is FetchMiddleware => Boolean(x)),\n });\n}\n\nfunction baseImplementation(\n options: MockFetchApiOptions | undefined,\n): typeof crossFetch {\n const implementation = options?.baseImplementation;\n if (!implementation) {\n return crossFetch;\n } else if (implementation === 'none') {\n return () => Promise.resolve(new Response());\n }\n return implementation;\n}\n\nfunction resolvePluginProtocol(\n allOptions: MockFetchApiOptions | undefined,\n): FetchMiddleware | undefined {\n const options = allOptions?.resolvePluginProtocol;\n if (!options) {\n return undefined;\n }\n\n return FetchMiddlewares.resolvePluginProtocol({\n discoveryApi: options.discoveryApi,\n });\n}\n\nfunction injectIdentityAuth(\n allOptions: MockFetchApiOptions | undefined,\n): FetchMiddleware | undefined {\n const options = allOptions?.injectIdentityAuth;\n if (!options) {\n return undefined;\n }\n\n const identityApi: Pick<IdentityApi, 'getCredentials'> =\n 'token' in options\n ? { getCredentials: async () => ({ token: options.token }) }\n : options.identityApi;\n\n return FetchMiddlewares.injectIdentityAuth({\n identityApi: identityApi as IdentityApi,\n allowUrl: () => true,\n });\n}\n"],"names":[],"mappings":";;;AA8FO,MAAM,YAAiC,CAAA;AAAA,EAC3B,cAAA
|
|
1
|
+
{"version":3,"file":"MockFetchApi.esm.js","sources":["../../../../src/testUtils/apis/FetchApi/MockFetchApi.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createFetchApi,\n FetchMiddleware,\n FetchMiddlewares,\n} from '@backstage/core-app-api';\nimport {\n DiscoveryApi,\n FetchApi,\n IdentityApi,\n} from '@backstage/core-plugin-api';\nimport crossFetch, { Response } from 'cross-fetch';\n\n/**\n * The options given when constructing a {@link MockFetchApi}.\n *\n * @public\n */\nexport interface MockFetchApiOptions {\n /**\n * Define the underlying base `fetch` implementation.\n *\n * @defaultValue undefined\n * @remarks\n *\n * Leaving out this parameter or passing `undefined`, makes the API use the\n * global `fetch` implementation to make real network requests.\n *\n * `'none'` swallows all calls and makes no requests at all.\n *\n * You can also pass in any `fetch` compatible callback, such as a\n * `jest.fn()`, if you want to use a custom implementation or to just track\n * and assert on calls.\n */\n baseImplementation?: undefined | 'none' | typeof crossFetch;\n\n /**\n * Add translation from `plugin://` URLs to concrete http(s) URLs, basically\n * simulating what\n * {@link @backstage/core-app-api#FetchMiddlewares.resolvePluginProtocol}\n * does.\n *\n * @defaultValue undefined\n * @remarks\n *\n * Leaving out this parameter or passing `undefined`, disables plugin protocol\n * translation.\n *\n * To enable the feature, pass in a discovery API which is then used to\n * resolve the URLs.\n */\n resolvePluginProtocol?:\n | undefined\n | { discoveryApi: Pick<DiscoveryApi, 'getBaseUrl'> };\n\n /**\n * Add token based Authorization headers to requests, basically simulating\n * what {@link @backstage/core-app-api#FetchMiddlewares.injectIdentityAuth}\n * does.\n *\n * @defaultValue undefined\n * @remarks\n *\n * Leaving out this parameter or passing `undefined`, disables auth injection.\n *\n * To enable the feature, pass in either a static token or an identity API\n * which is queried on each request for a token.\n */\n injectIdentityAuth?:\n | undefined\n | { token: string }\n | { identityApi: Pick<IdentityApi, 'getCredentials'> };\n}\n\n/**\n * A test helper implementation of {@link @backstage/core-plugin-api#FetchApi}.\n *\n * @public\n */\nexport class MockFetchApi implements FetchApi {\n private readonly implementation: FetchApi;\n\n /**\n * Creates a mock {@link @backstage/core-plugin-api#FetchApi}.\n */\n constructor(options?: MockFetchApiOptions) {\n this.implementation = build(options);\n }\n\n /** {@inheritdoc @backstage/core-plugin-api#FetchApi.fetch} */\n get fetch(): typeof crossFetch {\n return this.implementation.fetch;\n }\n}\n\n//\n// Helpers\n//\n\nfunction build(options?: MockFetchApiOptions): FetchApi {\n return createFetchApi({\n baseImplementation: baseImplementation(options),\n middleware: [\n resolvePluginProtocol(options),\n injectIdentityAuth(options),\n ].filter((x): x is FetchMiddleware => Boolean(x)),\n });\n}\n\nfunction baseImplementation(\n options: MockFetchApiOptions | undefined,\n): typeof crossFetch {\n const implementation = options?.baseImplementation;\n if (!implementation) {\n return crossFetch;\n } else if (implementation === 'none') {\n return () => Promise.resolve(new Response());\n }\n return implementation;\n}\n\nfunction resolvePluginProtocol(\n allOptions: MockFetchApiOptions | undefined,\n): FetchMiddleware | undefined {\n const options = allOptions?.resolvePluginProtocol;\n if (!options) {\n return undefined;\n }\n\n return FetchMiddlewares.resolvePluginProtocol({\n discoveryApi: options.discoveryApi,\n });\n}\n\nfunction injectIdentityAuth(\n allOptions: MockFetchApiOptions | undefined,\n): FetchMiddleware | undefined {\n const options = allOptions?.injectIdentityAuth;\n if (!options) {\n return undefined;\n }\n\n const identityApi: Pick<IdentityApi, 'getCredentials'> =\n 'token' in options\n ? { getCredentials: async () => ({ token: options.token }) }\n : options.identityApi;\n\n return FetchMiddlewares.injectIdentityAuth({\n identityApi: identityApi as IdentityApi,\n allowUrl: () => true,\n });\n}\n"],"names":[],"mappings":";;;AA8FO,MAAM,YAAiC,CAAA;AAAA,EAC3B,cAAA;AAAA;AAAA;AAAA;AAAA,EAKjB,YAAY,OAA+B,EAAA;AACzC,IAAK,IAAA,CAAA,cAAA,GAAiB,MAAM,OAAO,CAAA;AAAA;AACrC;AAAA,EAGA,IAAI,KAA2B,GAAA;AAC7B,IAAA,OAAO,KAAK,cAAe,CAAA,KAAA;AAAA;AAE/B;AAMA,SAAS,MAAM,OAAyC,EAAA;AACtD,EAAA,OAAO,cAAe,CAAA;AAAA,IACpB,kBAAA,EAAoB,mBAAmB,OAAO,CAAA;AAAA,IAC9C,UAAY,EAAA;AAAA,MACV,sBAAsB,OAAO,CAAA;AAAA,MAC7B,mBAAmB,OAAO;AAAA,MAC1B,MAAO,CAAA,CAAC,CAA4B,KAAA,OAAA,CAAQ,CAAC,CAAC;AAAA,GACjD,CAAA;AACH;AAEA,SAAS,mBACP,OACmB,EAAA;AACnB,EAAA,MAAM,iBAAiB,OAAS,EAAA,kBAAA;AAChC,EAAA,IAAI,CAAC,cAAgB,EAAA;AACnB,IAAO,OAAA,UAAA;AAAA,GACT,MAAA,IAAW,mBAAmB,MAAQ,EAAA;AACpC,IAAA,OAAO,MAAM,OAAA,CAAQ,OAAQ,CAAA,IAAI,UAAU,CAAA;AAAA;AAE7C,EAAO,OAAA,cAAA;AACT;AAEA,SAAS,sBACP,UAC6B,EAAA;AAC7B,EAAA,MAAM,UAAU,UAAY,EAAA,qBAAA;AAC5B,EAAA,IAAI,CAAC,OAAS,EAAA;AACZ,IAAO,OAAA,KAAA,CAAA;AAAA;AAGT,EAAA,OAAO,iBAAiB,qBAAsB,CAAA;AAAA,IAC5C,cAAc,OAAQ,CAAA;AAAA,GACvB,CAAA;AACH;AAEA,SAAS,mBACP,UAC6B,EAAA;AAC7B,EAAA,MAAM,UAAU,UAAY,EAAA,kBAAA;AAC5B,EAAA,IAAI,CAAC,OAAS,EAAA;AACZ,IAAO,OAAA,KAAA,CAAA;AAAA;AAGT,EAAA,MAAM,WACJ,GAAA,OAAA,IAAW,OACP,GAAA,EAAE,cAAgB,EAAA,aAAa,EAAE,KAAA,EAAO,OAAQ,CAAA,KAAA,EAAS,CAAA,EAAA,GACzD,OAAQ,CAAA,WAAA;AAEd,EAAA,OAAO,iBAAiB,kBAAmB,CAAA;AAAA,IACzC,WAAA;AAAA,IACA,UAAU,MAAM;AAAA,GACjB,CAAA;AACH;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MockPermissionApi.esm.js","sources":["../../../../src/testUtils/apis/PermissionApi/MockPermissionApi.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PermissionApi } from '@backstage/plugin-permission-react';\nimport {\n EvaluatePermissionResponse,\n EvaluatePermissionRequest,\n AuthorizeResult,\n} from '@backstage/plugin-permission-common';\n\n/**\n * Mock implementation of\n * {@link @backstage/plugin-permission-react#PermissionApi}. Supply a\n * requestHandler function to override the mock result returned for a given\n * request.\n * @deprecated Use {@link @backstage/test-utils#mockApis.(permission:namespace)} instead\n * @public\n */\nexport class MockPermissionApi implements PermissionApi {\n constructor(\n private readonly requestHandler: (\n request: EvaluatePermissionRequest,\n ) => AuthorizeResult.ALLOW | AuthorizeResult.DENY = () =>\n AuthorizeResult.ALLOW,\n ) {}\n\n async authorize(\n request: EvaluatePermissionRequest,\n ): Promise<EvaluatePermissionResponse> {\n return { result: this.requestHandler(request) };\n }\n}\n"],"names":[],"mappings":";;AA+BO,MAAM,iBAA2C,CAAA;AAAA,EACtD,WACmB,CAAA,cAAA,GAEmC,MAClD,eAAA,CAAgB,KAClB,EAAA;AAJiB,IAAA,IAAA,CAAA,cAAA,GAAA,cAAA
|
|
1
|
+
{"version":3,"file":"MockPermissionApi.esm.js","sources":["../../../../src/testUtils/apis/PermissionApi/MockPermissionApi.ts"],"sourcesContent":["/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PermissionApi } from '@backstage/plugin-permission-react';\nimport {\n EvaluatePermissionResponse,\n EvaluatePermissionRequest,\n AuthorizeResult,\n} from '@backstage/plugin-permission-common';\n\n/**\n * Mock implementation of\n * {@link @backstage/plugin-permission-react#PermissionApi}. Supply a\n * requestHandler function to override the mock result returned for a given\n * request.\n * @deprecated Use {@link @backstage/test-utils#mockApis.(permission:namespace)} instead\n * @public\n */\nexport class MockPermissionApi implements PermissionApi {\n constructor(\n private readonly requestHandler: (\n request: EvaluatePermissionRequest,\n ) => AuthorizeResult.ALLOW | AuthorizeResult.DENY = () =>\n AuthorizeResult.ALLOW,\n ) {}\n\n async authorize(\n request: EvaluatePermissionRequest,\n ): Promise<EvaluatePermissionResponse> {\n return { result: this.requestHandler(request) };\n }\n}\n"],"names":[],"mappings":";;AA+BO,MAAM,iBAA2C,CAAA;AAAA,EACtD,WACmB,CAAA,cAAA,GAEmC,MAClD,eAAA,CAAgB,KAClB,EAAA;AAJiB,IAAA,IAAA,CAAA,cAAA,GAAA,cAAA;AAAA;AAIhB,EAEH,MAAM,UACJ,OACqC,EAAA;AACrC,IAAA,OAAO,EAAE,MAAA,EAAQ,IAAK,CAAA,cAAA,CAAe,OAAO,CAAE,EAAA;AAAA;AAElD;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MockStorageApi.esm.js","sources":["../../../../src/testUtils/apis/StorageApi/MockStorageApi.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { StorageApi, StorageValueSnapshot } from '@backstage/core-plugin-api';\nimport { JsonValue, Observable } from '@backstage/types';\nimport ObservableImpl from 'zen-observable';\n\n/**\n * Type for map holding data in {@link MockStorageApi}\n * @deprecated Use {@link @backstage/test-utils#mockApis.(storage:namespace)} instead\n * @public\n */\nexport type MockStorageBucket = { [key: string]: any };\n\n/**\n * Mock implementation of the {@link core-plugin-api#StorageApi} to be used in tests\n * @deprecated Use {@link @backstage/test-utils#mockApis.(storage:namespace)} instead\n * @public\n */\nexport class MockStorageApi implements StorageApi {\n private readonly namespace: string;\n private readonly data: MockStorageBucket;\n private readonly bucketStorageApis: Map<string, MockStorageApi>;\n\n private constructor(\n namespace: string,\n bucketStorageApis: Map<string, MockStorageApi>,\n data?: MockStorageBucket,\n ) {\n this.namespace = namespace;\n this.bucketStorageApis = bucketStorageApis;\n this.data = { ...data };\n }\n\n static create(data?: MockStorageBucket) {\n // Translate a nested data object structure into a flat object with keys\n // like `/a/b` with their corresponding leaf values\n const keyValues: { [key: string]: any } = {};\n function put(value: { [key: string]: any }, namespace: string) {\n for (const [key, val] of Object.entries(value)) {\n if (typeof val === 'object' && val !== null) {\n put(val, `${namespace}/${key}`);\n } else {\n const namespacedKey = `${namespace}/${key.replace(/^\\//, '')}`;\n keyValues[namespacedKey] = val;\n }\n }\n }\n put(data ?? {}, '');\n return new MockStorageApi('', new Map(), keyValues);\n }\n\n forBucket(name: string): StorageApi {\n if (!this.bucketStorageApis.has(name)) {\n this.bucketStorageApis.set(\n name,\n new MockStorageApi(\n `${this.namespace}/${name}`,\n this.bucketStorageApis,\n this.data,\n ),\n );\n }\n return this.bucketStorageApis.get(name)!;\n }\n\n snapshot<T extends JsonValue>(key: string): StorageValueSnapshot<T> {\n if (this.data.hasOwnProperty(this.getKeyName(key))) {\n const data = this.data[this.getKeyName(key)];\n return {\n key,\n presence: 'present',\n value: data,\n };\n }\n return {\n key,\n presence: 'absent',\n value: undefined,\n };\n }\n\n async set<T>(key: string, data: T): Promise<void> {\n const serialized = JSON.parse(JSON.stringify(data), (_key, value) => {\n if (typeof value === 'object' && value !== null) {\n Object.freeze(value);\n }\n return value;\n });\n this.data[this.getKeyName(key)] = serialized;\n this.notifyChanges({\n key,\n presence: 'present',\n value: serialized,\n });\n }\n\n async remove(key: string): Promise<void> {\n delete this.data[this.getKeyName(key)];\n this.notifyChanges({\n key,\n presence: 'absent',\n value: undefined,\n });\n }\n\n observe$<T extends JsonValue>(\n key: string,\n ): Observable<StorageValueSnapshot<T>> {\n return this.observable.filter(({ key: messageKey }) => messageKey === key);\n }\n\n private getKeyName(key: string) {\n return `${this.namespace}/${encodeURIComponent(key)}`;\n }\n\n private notifyChanges<T extends JsonValue>(message: StorageValueSnapshot<T>) {\n for (const subscription of this.subscribers) {\n subscription.next(message);\n }\n }\n\n private subscribers = new Set<\n ZenObservable.SubscriptionObserver<StorageValueSnapshot<JsonValue>>\n >();\n\n private readonly observable = new ObservableImpl<\n StorageValueSnapshot<JsonValue>\n >(subscriber => {\n this.subscribers.add(subscriber);\n return () => {\n this.subscribers.delete(subscriber);\n };\n });\n}\n"],"names":[],"mappings":";;AAgCO,MAAM,cAAqC,CAAA;AAAA,EAC/B,SAAA
|
|
1
|
+
{"version":3,"file":"MockStorageApi.esm.js","sources":["../../../../src/testUtils/apis/StorageApi/MockStorageApi.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { StorageApi, StorageValueSnapshot } from '@backstage/core-plugin-api';\nimport { JsonValue, Observable } from '@backstage/types';\nimport ObservableImpl from 'zen-observable';\n\n/**\n * Type for map holding data in {@link MockStorageApi}\n * @deprecated Use {@link @backstage/test-utils#mockApis.(storage:namespace)} instead\n * @public\n */\nexport type MockStorageBucket = { [key: string]: any };\n\n/**\n * Mock implementation of the {@link core-plugin-api#StorageApi} to be used in tests\n * @deprecated Use {@link @backstage/test-utils#mockApis.(storage:namespace)} instead\n * @public\n */\nexport class MockStorageApi implements StorageApi {\n private readonly namespace: string;\n private readonly data: MockStorageBucket;\n private readonly bucketStorageApis: Map<string, MockStorageApi>;\n\n private constructor(\n namespace: string,\n bucketStorageApis: Map<string, MockStorageApi>,\n data?: MockStorageBucket,\n ) {\n this.namespace = namespace;\n this.bucketStorageApis = bucketStorageApis;\n this.data = { ...data };\n }\n\n static create(data?: MockStorageBucket) {\n // Translate a nested data object structure into a flat object with keys\n // like `/a/b` with their corresponding leaf values\n const keyValues: { [key: string]: any } = {};\n function put(value: { [key: string]: any }, namespace: string) {\n for (const [key, val] of Object.entries(value)) {\n if (typeof val === 'object' && val !== null) {\n put(val, `${namespace}/${key}`);\n } else {\n const namespacedKey = `${namespace}/${key.replace(/^\\//, '')}`;\n keyValues[namespacedKey] = val;\n }\n }\n }\n put(data ?? {}, '');\n return new MockStorageApi('', new Map(), keyValues);\n }\n\n forBucket(name: string): StorageApi {\n if (!this.bucketStorageApis.has(name)) {\n this.bucketStorageApis.set(\n name,\n new MockStorageApi(\n `${this.namespace}/${name}`,\n this.bucketStorageApis,\n this.data,\n ),\n );\n }\n return this.bucketStorageApis.get(name)!;\n }\n\n snapshot<T extends JsonValue>(key: string): StorageValueSnapshot<T> {\n if (this.data.hasOwnProperty(this.getKeyName(key))) {\n const data = this.data[this.getKeyName(key)];\n return {\n key,\n presence: 'present',\n value: data,\n };\n }\n return {\n key,\n presence: 'absent',\n value: undefined,\n };\n }\n\n async set<T>(key: string, data: T): Promise<void> {\n const serialized = JSON.parse(JSON.stringify(data), (_key, value) => {\n if (typeof value === 'object' && value !== null) {\n Object.freeze(value);\n }\n return value;\n });\n this.data[this.getKeyName(key)] = serialized;\n this.notifyChanges({\n key,\n presence: 'present',\n value: serialized,\n });\n }\n\n async remove(key: string): Promise<void> {\n delete this.data[this.getKeyName(key)];\n this.notifyChanges({\n key,\n presence: 'absent',\n value: undefined,\n });\n }\n\n observe$<T extends JsonValue>(\n key: string,\n ): Observable<StorageValueSnapshot<T>> {\n return this.observable.filter(({ key: messageKey }) => messageKey === key);\n }\n\n private getKeyName(key: string) {\n return `${this.namespace}/${encodeURIComponent(key)}`;\n }\n\n private notifyChanges<T extends JsonValue>(message: StorageValueSnapshot<T>) {\n for (const subscription of this.subscribers) {\n subscription.next(message);\n }\n }\n\n private subscribers = new Set<\n ZenObservable.SubscriptionObserver<StorageValueSnapshot<JsonValue>>\n >();\n\n private readonly observable = new ObservableImpl<\n StorageValueSnapshot<JsonValue>\n >(subscriber => {\n this.subsc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V,KAAO,EAAA;AAAA,KACR,CAAA;AAAA;AACH,EAEA,MAAM,OAAO,GAA4B,EAAA;AACvC,IAAA,OAAO,IAAK,CAAA,IAAA,CAAK,IAAK,CAAA,UAAA,CAAW,GAAG,CAAC,CAAA;AACrC,IAAA,IAAA,CAAK,aAAc,CAAA;AAAA,MACjB,GAAA;AAAA,MACA,QAAU,EAAA,QAAA;AAAA,MACV,KAAO,EAAA,KAAA;AAAA,KACR,CAAA;AAAA;AACH,EAEA,SACE,GACqC,EAAA;AACrC,IAAO,OAAA,IAAA,CAAK,WAAW,MAAO,CAAA,CAAC,EAAE,GAAK,EAAA,UAAA,EAAiB,KAAA,UAAA,KAAe,GAAG,CAAA;AAAA;AAC3E,EAEQ,WAAW,GAAa,EAAA;AAC9B,IAAA,OAAO,GAAG,IAAK,CAAA,SAAS,CAAI,CAAA,EAAA,kBAAA,CAAmB,GAAG,CAAC,CAAA,CAAA;AAAA;AACrD,EAEQ,cAAmC,OAAkC,EAAA;AAC3E,IAAW,KAAA,MAAA,YAAA,IAAgB,KAAK,WAAa,EAAA;AAC3C,MAAA,YAAA,CAAa,KAAK,OAAO,CAAA;AAAA;AAC3B;AACF,EAEQ,WAAA,uBAAkB,GAExB,EAAA;AAAA,EAEe,UAAA,GAAa,IAAI,cAAA,CAEhC,CAAc,UAAA,KAAA;AACd,IAAK,IAAA,CAAA,WAAA,CAAY,IAAI,UAAU,CAAA;AAC/B,IAAA,OAAO,MAAM;AACX,MAAK,IAAA,CAAA,WAAA,CAAY,OAAO,UAAU,CAAA;AAAA,KACpC;AAAA,GACD,CAAA;AACH;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MockTranslationApi.esm.js","sources":["../../../../src/testUtils/apis/TranslationApi/MockTranslationApi.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n TranslationApi,\n TranslationFunction,\n TranslationRef,\n TranslationSnapshot,\n} from '@backstage/core-plugin-api/alpha';\nimport { createInstance as createI18n, type i18n as I18n } from 'i18next';\nimport ObservableImpl from 'zen-observable';\n\nimport { Observable } from '@backstage/types';\n// Internal import to avoid code duplication, this will lead to duplication in build output\n// eslint-disable-next-line @backstage/no-relative-monorepo-imports\nimport { toInternalTranslationRef } from '../../../../../core-plugin-api/src/translation/TranslationRef';\n\nconst DEFAULT_LANGUAGE = 'en';\n\n/**\n * @alpha\n * @deprecated Use `mockApis` from `@backstage/test-utils` instead\n */\nexport class MockTranslationApi implements TranslationApi {\n static create() {\n const i18n = createI18n({\n fallbackLng: DEFAULT_LANGUAGE,\n supportedLngs: [DEFAULT_LANGUAGE],\n interpolation: {\n escapeValue: false,\n },\n ns: [],\n defaultNS: false,\n fallbackNS: false,\n\n // Disable resource loading on init, meaning i18n will be ready to use immediately\n initImmediate: false,\n });\n\n i18n.init();\n if (!i18n.isInitialized) {\n throw new Error('i18next was unexpectedly not initialized');\n }\n\n return new MockTranslationApi(i18n);\n }\n\n #i18n: I18n;\n #registeredRefs = new Set<string>();\n\n private constructor(i18n: I18n) {\n this.#i18n = i18n;\n }\n\n getTranslation<TMessages extends { [key in string]: string }>(\n translationRef: TranslationRef<string, TMessages>,\n ): TranslationSnapshot<TMessages> {\n const internalRef = toInternalTranslationRef(translationRef);\n\n if (!this.#registeredRefs.has(internalRef.id)) {\n this.#registeredRefs.add(internalRef.id);\n this.#i18n.addResourceBundle(\n DEFAULT_LANGUAGE,\n internalRef.id,\n internalRef.getDefaultMessages(),\n false, // do not merge\n true, // overwrite existing\n );\n }\n\n const t = this.#i18n.getFixedT(\n null,\n internalRef.id,\n ) as TranslationFunction<TMessages>;\n\n return {\n ready: true,\n t,\n };\n }\n\n translation$<TMessages extends { [key in string]: string }>(): Observable<\n TranslationSnapshot<TMessages>\n > {\n // No need to implement, getTranslation will always return a ready snapshot\n return new ObservableImpl<TranslationSnapshot<TMessages>>(_subscriber => {\n return () => {};\n });\n }\n}\n"],"names":["createI18n"],"mappings":";;;;AA8BA,MAAM,gBAAmB,GAAA,IAAA
|
|
1
|
+
{"version":3,"file":"MockTranslationApi.esm.js","sources":["../../../../src/testUtils/apis/TranslationApi/MockTranslationApi.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n TranslationApi,\n TranslationFunction,\n TranslationRef,\n TranslationSnapshot,\n} from '@backstage/core-plugin-api/alpha';\nimport { createInstance as createI18n, type i18n as I18n } from 'i18next';\nimport ObservableImpl from 'zen-observable';\n\nimport { Observable } from '@backstage/types';\n// Internal import to avoid code duplication, this will lead to duplication in build output\n// eslint-disable-next-line @backstage/no-relative-monorepo-imports\nimport { toInternalTranslationRef } from '../../../../../core-plugin-api/src/translation/TranslationRef';\n\nconst DEFAULT_LANGUAGE = 'en';\n\n/**\n * @alpha\n * @deprecated Use `mockApis` from `@backstage/test-utils` instead\n */\nexport class MockTranslationApi implements TranslationApi {\n static create() {\n const i18n = createI18n({\n fallbackLng: DEFAULT_LANGUAGE,\n supportedLngs: [DEFAULT_LANGUAGE],\n interpolation: {\n escapeValue: false,\n },\n ns: [],\n defaultNS: false,\n fallbackNS: false,\n\n // Disable resource loading on init, meaning i18n will be ready to use immediately\n initImmediate: false,\n });\n\n i18n.init();\n if (!i18n.isInitialized) {\n throw new Error('i18next was unexpectedly not initialized');\n }\n\n return new MockTranslationApi(i18n);\n }\n\n #i18n: I18n;\n #registeredRefs = new Set<string>();\n\n private constructor(i18n: I18n) {\n this.#i18n = i18n;\n }\n\n getTranslation<TMessages extends { [key in string]: string }>(\n translationRef: TranslationRef<string, TMessages>,\n ): TranslationSnapshot<TMessages> {\n const internalRef = toInternalTranslationRef(translationRef);\n\n if (!this.#registeredRefs.has(internalRef.id)) {\n this.#registeredRefs.add(internalRef.id);\n this.#i18n.addResourceBundle(\n DEFAULT_LANGUAGE,\n internalRef.id,\n internalRef.getDefaultMessages(),\n false, // do not merge\n true, // overwrite existing\n );\n }\n\n const t = this.#i18n.getFixedT(\n null,\n internalRef.id,\n ) as TranslationFunction<TMessages>;\n\n return {\n ready: true,\n t,\n };\n }\n\n translation$<TMessages extends { [key in string]: string }>(): Observable<\n TranslationSnapshot<TMessages>\n > {\n // No need to implement, getTranslation will always return a ready snapshot\n return new ObservableImpl<TranslationSnapshot<TMessages>>(_subscriber => {\n return () => {};\n });\n }\n}\n"],"names":["createI18n"],"mappings":";;;;AA8BA,MAAM,gBAAmB,GAAA,IAAA;AAMlB,MAAM,kBAA6C,CAAA;AAAA,EACxD,OAAO,MAAS,GAAA;AACd,IAAA,MAAM,OAAOA,cAAW,CAAA;AAAA,MACtB,WAAa,EAAA,gBAAA;AAAA,MACb,aAAA,EAAe,CAAC,gBAAgB,CAAA;AAAA,MAChC,aAAe,EAAA;AAAA,QACb,WAAa,EAAA;AAAA,OACf;AAAA,MACA,IAAI,EAAC;AAAA,MACL,SAAW,EAAA,KAAA;AAAA,MACX,UAAY,EAAA,KAAA;AAAA;AAAA,MAGZ,aAAe,EAAA;AAAA,KAChB,CAAA;AAED,IAAA,IAAA,CAAK,IAAK,EAAA;AACV,IAAI,IAAA,CAAC,KAAK,aAAe,EAAA;AACvB,MAAM,MAAA,IAAI,MAAM,0CAA0C,CAAA;AAAA;AAG5D,IAAO,OAAA,IAAI,mBAAmB,IAAI,CAAA;AAAA;AACpC,EAEA,KAAA;AAAA,EACA,eAAA,uBAAsB,GAAY,EAAA;AAAA,EAE1B,YAAY,IAAY,EAAA;AAC9B,IAAA,IAAA,CAAK,KAAQ,GAAA,IAAA;AAAA;AACf,EAEA,eACE,cACgC,EAAA;AAChC,IAAM,MAAA,WAAA,GAAc,yBAAyB,cAAc,CAAA;AAE3D,IAAA,IAAI,CAAC,IAAK,CAAA,eAAA,CAAgB,GAAI,CAAA,WAAA,CAAY,EAAE,CAAG,EAAA;AAC7C,MAAK,IAAA,CAAA,eAAA,CAAgB,GAAI,CAAA,WAAA,CAAY,EAAE,CAAA;AACvC,MAAA,IAAA,CAAK,KAAM,CAAA,iBAAA;AAAA,QACT,gBAAA;AAAA,QACA,WAAY,CAAA,EAAA;AAAA,QACZ,YAAY,kBAAmB,EAAA;AAAA,QAC/B,KAAA;AAAA;AAAA,QACA;AAAA;AAAA,OACF;AAAA;AAGF,IAAM,MAAA,CAAA,GAAI,KAAK,KAAM,CAAA,SAAA;AAAA,MACnB,IAAA;AAAA,MACA,WAAY,CAAA;AAAA,KACd;AAEA,IAAO,OAAA;AAAA,MACL,KAAO,EAAA,IAAA;AAAA,MACP;AAAA,KACF;AAAA;AACF,EAEA,YAEE,GAAA;AAEA,IAAO,OAAA,IAAI,eAA+C,CAAe,WAAA,KAAA;AACvE,MAAA,OAAO,MAAM;AAAA,OAAC;AAAA,KACf,CAAA;AAAA;AAEL;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mockApis.esm.js","sources":["../../../src/testUtils/apis/mockApis.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ConfigReader } from '@backstage/config';\nimport {\n AnalyticsApi,\n ApiFactory,\n ApiRef,\n ConfigApi,\n DiscoveryApi,\n IdentityApi,\n StorageApi,\n analyticsApiRef,\n configApiRef,\n createApiFactory,\n discoveryApiRef,\n identityApiRef,\n storageApiRef,\n} from '@backstage/core-plugin-api';\nimport {\n TranslationApi,\n translationApiRef,\n} from '@backstage/core-plugin-api/alpha';\nimport {\n AuthorizeResult,\n EvaluatePermissionRequest,\n} from '@backstage/plugin-permission-common';\nimport {\n PermissionApi,\n permissionApiRef,\n} from '@backstage/plugin-permission-react';\nimport { JsonObject } from '@backstage/types';\nimport { ApiMock } from './ApiMock';\nimport { MockPermissionApi } from './PermissionApi';\nimport { MockStorageApi } from './StorageApi';\nimport { MockTranslationApi } from './TranslationApi';\n\n/** @internal */\nfunction simpleFactory<TApi, TArgs extends unknown[]>(\n ref: ApiRef<TApi>,\n factory: (...args: TArgs) => TApi,\n): (...args: TArgs) => ApiFactory<TApi, TApi, {}> {\n return (...args) =>\n createApiFactory({\n api: ref,\n deps: {},\n factory: () => factory(...args),\n });\n}\n\n/** @internal */\nfunction simpleMock<TApi>(\n ref: ApiRef<TApi>,\n mockFactory: () => jest.Mocked<TApi>,\n): (partialImpl?: Partial<TApi>) => ApiMock<TApi> {\n return partialImpl => {\n const mock = mockFactory();\n if (partialImpl) {\n for (const [key, impl] of Object.entries(partialImpl)) {\n if (typeof impl === 'function') {\n (mock as any)[key].mockImplementation(impl);\n } else {\n (mock as any)[key] = impl;\n }\n }\n }\n return Object.assign(mock, {\n factory: createApiFactory({\n api: ref,\n deps: {},\n factory: () => mock,\n }),\n }) as ApiMock<TApi>;\n };\n}\n\n/**\n * Mock implementations of the core utility APIs, to be used in tests.\n *\n * @public\n * @remarks\n *\n * There are some variations among the APIs depending on what needs tests\n * might have, but overall there are three main usage patterns:\n *\n * 1: Creating an actual fake API instance, often with a simplified version\n * of functionality, by calling the mock API itself as a function.\n *\n * ```ts\n * // The function often accepts parameters that control its behavior\n * const foo = mockApis.foo();\n * ```\n *\n * 2: Creating a mock API, where all methods are replaced with jest mocks, by\n * calling the API's `mock` function.\n *\n * ```ts\n * // You can optionally supply a subset of its methods to implement\n * const foo = mockApis.foo.mock({\n * someMethod: () => 'mocked result',\n * });\n * // After exercising your test, you can make assertions on the mock:\n * expect(foo.someMethod).toHaveBeenCalledTimes(2);\n * expect(foo.otherMethod).toHaveBeenCalledWith(testData);\n * ```\n *\n * 3: Creating an API factory that behaves similarly to the mock as per above.\n *\n * ```ts\n * const factory = mockApis.foo.factory({\n * someMethod: () => 'mocked result',\n * });\n * ```\n */\nexport namespace mockApis {\n const analyticsMockSkeleton = (): jest.Mocked<AnalyticsApi> => ({\n captureEvent: jest.fn(),\n });\n /**\n * Mock implementation of {@link @backstage/core-plugin-api#AnalyticsApi}.\n *\n * @public\n */\n export function analytics(): AnalyticsApi {\n return analyticsMockSkeleton();\n }\n /**\n * Mock implementations of {@link @backstage/core-plugin-api#AnalyticsApi}.\n *\n * @public\n */\n export namespace analytics {\n export const factory = simpleFactory(analyticsApiRef, analytics);\n export const mock = simpleMock(analyticsApiRef, analyticsMockSkeleton);\n }\n\n /**\n * Fake implementation of {@link @backstage/core-plugin-api#ConfigApi}\n * with optional data supplied.\n *\n * @public\n * @example\n *\n * ```tsx\n * const config = mockApis.config({\n * data: { app: { baseUrl: 'https://example.com' } },\n * });\n *\n * await renderInTestApp(\n * <TestApiProvider apis={[[configApiRef, config]]}>\n * <MyTestedComponent />\n * </TestApiProvider>,\n * );\n * ```\n */\n export function config(options?: { data?: JsonObject }): ConfigApi {\n return new ConfigReader(options?.data, 'mock-config');\n }\n /**\n * Mock helpers for {@link @backstage/core-plugin-api#ConfigApi}.\n *\n * @see {@link @backstage/core-plugin-api#mockApis.config}\n * @public\n */\n export namespace config {\n /**\n * Creates a factory for a fake implementation of\n * {@link @backstage/core-plugin-api#ConfigApi} with optional\n * configuration data supplied.\n *\n * @public\n */\n export const factory = simpleFactory(configApiRef, config);\n /**\n * Creates a mock implementation of\n * {@link @backstage/core-plugin-api#ConfigApi}. All methods are\n * replaced with jest mock functions, and you can optionally pass in a\n * subset of methods with an explicit implementation.\n *\n * @public\n */\n export const mock = simpleMock(configApiRef, () => ({\n has: jest.fn(),\n keys: jest.fn(),\n get: jest.fn(),\n getOptional: jest.fn(),\n getConfig: jest.fn(),\n getOptionalConfig: jest.fn(),\n getConfigArray: jest.fn(),\n getOptionalConfigArray: jest.fn(),\n getNumber: jest.fn(),\n getOptionalNumber: jest.fn(),\n getBoolean: jest.fn(),\n getOptionalBoolean: jest.fn(),\n getString: jest.fn(),\n getOptionalString: jest.fn(),\n getStringArray: jest.fn(),\n getOptionalStringArray: jest.fn(),\n }));\n }\n\n /**\n * Fake implementation of {@link @backstage/core-plugin-api#DiscoveryApi}. By\n * default returns URLs on the form `http://example.com/api/<pluginIs>`.\n *\n * @public\n */\n export function discovery(options?: { baseUrl?: string }): DiscoveryApi {\n const baseUrl = options?.baseUrl ?? 'http://example.com';\n return {\n async getBaseUrl(pluginId: string) {\n return `${baseUrl}/api/${pluginId}`;\n },\n };\n }\n /**\n * Mock implementations of {@link @backstage/core-plugin-api#DiscoveryApi}.\n *\n * @public\n */\n export namespace discovery {\n export const factory = simpleFactory(discoveryApiRef, discovery);\n export const mock = simpleMock(discoveryApiRef, () => ({\n getBaseUrl: jest.fn(),\n }));\n }\n\n /**\n * Fake implementation of {@link @backstage/core-plugin-api#IdentityApi}. By\n * default returns no token or profile info, and the user `user:default/test`.\n *\n * @public\n */\n export function identity(options?: {\n userEntityRef?: string;\n ownershipEntityRefs?: string[];\n token?: string;\n email?: string;\n displayName?: string;\n picture?: string;\n }): IdentityApi {\n const {\n userEntityRef = 'user:default/test',\n ownershipEntityRefs = ['user:default/test'],\n token,\n email,\n displayName,\n picture,\n } = options ?? {};\n return {\n async getBackstageIdentity() {\n return { type: 'user', ownershipEntityRefs, userEntityRef };\n },\n async getCredentials() {\n return { token };\n },\n async getProfileInfo() {\n return { email, displayName, picture };\n },\n async signOut() {},\n };\n }\n /**\n * Mock implementations of {@link @backstage/core-plugin-api#IdentityApi}.\n *\n * @public\n */\n export namespace identity {\n export const factory = simpleFactory(identityApiRef, identity);\n export const mock = simpleMock(\n identityApiRef,\n (): jest.Mocked<IdentityApi> => ({\n getBackstageIdentity: jest.fn(),\n getCredentials: jest.fn(),\n getProfileInfo: jest.fn(),\n signOut: jest.fn(),\n }),\n );\n }\n\n /**\n * Fake implementation of\n * {@link @backstage/plugin-permission-react#PermissionApi}. By default allows\n * all actions.\n *\n * @public\n */\n export function permission(options?: {\n authorize?:\n | AuthorizeResult.ALLOW\n | AuthorizeResult.DENY\n | ((\n request: EvaluatePermissionRequest,\n ) => AuthorizeResult.ALLOW | AuthorizeResult.DENY);\n }): PermissionApi {\n const authorizeInput = options?.authorize;\n let authorize: (\n request: EvaluatePermissionRequest,\n ) => AuthorizeResult.ALLOW | AuthorizeResult.DENY;\n if (authorizeInput === undefined) {\n authorize = () => AuthorizeResult.ALLOW;\n } else if (typeof authorizeInput === 'function') {\n authorize = authorizeInput;\n } else {\n authorize = () => authorizeInput;\n }\n return new MockPermissionApi(authorize);\n }\n /**\n * Mock implementation of\n * {@link @backstage/plugin-permission-react#PermissionApi}.\n *\n * @public\n */\n export namespace permission {\n export const factory = simpleFactory(permissionApiRef, permission);\n export const mock = simpleMock(permissionApiRef, () => ({\n authorize: jest.fn(),\n }));\n }\n\n /**\n * Fake implementation of {@link @backstage/core-plugin-api#StorageApi}.\n * Stores data temporarily in memory.\n *\n * @public\n */\n export function storage(options?: { data?: JsonObject }): StorageApi {\n return MockStorageApi.create(options?.data);\n }\n /**\n * Mock implementations of {@link @backstage/core-plugin-api#StorageApi}.\n *\n * @public\n */\n export namespace storage {\n export const factory = simpleFactory(storageApiRef, storage);\n export const mock = simpleMock(storageApiRef, () => ({\n forBucket: jest.fn(),\n set: jest.fn(),\n remove: jest.fn(),\n observe$: jest.fn(),\n snapshot: jest.fn(),\n }));\n }\n\n /**\n * Fake implementation of {@link @backstage/core-plugin-api/alpha#TranslationApi}.\n * By default returns the default translation.\n *\n * @public\n */\n export function translation(): TranslationApi {\n return MockTranslationApi.create();\n }\n /**\n * Mock implementations of {@link @backstage/core-plugin-api/alpha#TranslationApi}.\n *\n * @public\n */\n export namespace translation {\n export const factory = simpleFactory(translationApiRef, translation);\n export const mock = simpleMock(translationApiRef, () => ({\n getTranslation: jest.fn(),\n translation$: jest.fn(),\n }));\n }\n}\n"],"names":["mockApis","analytics","config","discovery","identity","permission","storage","translation"],"mappings":";;;;;;;;;AAmDA,SAAS,aAAA,CACP,KACA,OACgD,EAAA;AAChD,EAAO,OAAA,CAAA,GAAI,SACT,gBAAiB,CAAA;AAAA,IACf,GAAK,EAAA,GAAA;AAAA,IACL,MAAM,EAAC;AAAA,IACP,OAAS,EAAA,MAAM,OAAQ,CAAA,GAAG,IAAI,CAAA;AAAA,GAC/B,CAAA,CAAA;AACL,CAAA;AAGA,SAAS,UAAA,CACP,KACA,WACgD,EAAA;AAChD,EAAA,OAAO,CAAe,WAAA,KAAA;AACpB,IAAA,MAAM,OAAO,WAAY,EAAA,CAAA;AACzB,IAAA,IAAI,WAAa,EAAA;AACf,MAAA,KAAA,MAAW,CAAC,GAAK,EAAA,IAAI,KAAK,MAAO,CAAA,OAAA,CAAQ,WAAW,CAAG,EAAA;AACrD,QAAI,IAAA,OAAO,SAAS,UAAY,EAAA;AAC9B,UAAC,IAAa,CAAA,GAAG,CAAE,CAAA,kBAAA,CAAmB,IAAI,CAAA,CAAA;AAAA,SACrC,MAAA;AACL,UAAC,IAAA,CAAa,GAAG,CAAI,GAAA,IAAA,CAAA;AAAA,SACvB;AAAA,OACF;AAAA,KACF;AACA,IAAO,OAAA,MAAA,CAAO,OAAO,IAAM,EAAA;AAAA,MACzB,SAAS,g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AAA,OAAA,GAAU,aAAc,CAAA,aAAA,EAAeA,QAAO,CAAA,CAAA;AACpD,IAAMA,QAAA,CAAA,IAAA,GAAO,UAAW,CAAA,aAAA,EAAe,OAAO;AAAA,MACnD,SAAA,EAAW,KAAK,EAAG,EAAA;AAAA,MACnB,GAAA,EAAK,KAAK,EAAG,EAAA;AAAA,MACb,MAAA,EAAQ,KAAK,EAAG,EAAA;AAAA,MAChB,QAAA,EAAU,KAAK,EAAG,EAAA;AAAA,MAClB,QAAA,EAAU,KAAK,EAAG,EAAA;AAAA,KAClB,CAAA,CAAA,CAAA;AAAA,GARa,EAAA,OAAA,GAAAN,SAAA,CAAA,OAAA,KAAAA,SAAA,CAAA,OAAA,GAAA,EAAA,CAAA,CAAA,CAAA;AAiBV,EAAA,SAAS,WAA8B,GAAA;AAC5C,IAAA,OAAO,mBAAmB,MAAO,EAAA,CAAA;AAAA,GACnC;AAFO,EAAAA,SAAS,CAAA,WAAA,GAAA,WAAA,CAAA;AAQT,EAAA,CAAA,CAAUO,YAAV,KAAA;AACE,IAAMA,YAAA,CAAA,OAAA,GAAU,aAAc,CAAA,iBAAA,EAAmBA,YAAW,CAAA,CAAA;AAC5D,IAAMA,YAAA,CAAA,IAAA,GAAO,UAAW,CAAA,iBAAA,EAAmB,OAAO;AAAA,MACvD,cAAA,EAAgB,KAAK,EAAG,EAAA;AAAA,MACxB,YAAA,EAAc,KAAK,EAAG,EAAA;AAAA,KACtB,CAAA,CAAA,CAAA;AAAA,GALa,EAAA,WAAA,GAAAP,SAAA,CAAA,WAAA,KAAAA,SAAA,CAAA,WAAA,GAAA,EAAA,CAAA,CAAA,CAAA;AAAA,CAtPF,EAAA,QAAA,KAAA,QAAA,GAAA,EAAA,CAAA,CAAA;;;;"}
|
|
1
|
+
{"version":3,"file":"mockApis.esm.js","sources":["../../../src/testUtils/apis/mockApis.ts"],"sourcesContent":["/*\n * Copyright 2024 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ConfigReader } from '@backstage/config';\nimport {\n AnalyticsApi,\n ApiFactory,\n ApiRef,\n ConfigApi,\n DiscoveryApi,\n IdentityApi,\n StorageApi,\n analyticsApiRef,\n configApiRef,\n createApiFactory,\n discoveryApiRef,\n identityApiRef,\n storageApiRef,\n} from '@backstage/core-plugin-api';\nimport {\n TranslationApi,\n translationApiRef,\n} from '@backstage/core-plugin-api/alpha';\nimport {\n AuthorizeResult,\n EvaluatePermissionRequest,\n} from '@backstage/plugin-permission-common';\nimport {\n PermissionApi,\n permissionApiRef,\n} from '@backstage/plugin-permission-react';\nimport { JsonObject } from '@backstage/types';\nimport { ApiMock } from './ApiMock';\nimport { MockPermissionApi } from './PermissionApi';\nimport { MockStorageApi } from './StorageApi';\nimport { MockTranslationApi } from './TranslationApi';\n\n/** @internal */\nfunction simpleFactory<TApi, TArgs extends unknown[]>(\n ref: ApiRef<TApi>,\n factory: (...args: TArgs) => TApi,\n): (...args: TArgs) => ApiFactory<TApi, TApi, {}> {\n return (...args) =>\n createApiFactory({\n api: ref,\n deps: {},\n factory: () => factory(...args),\n });\n}\n\n/** @internal */\nfunction simpleMock<TApi>(\n ref: ApiRef<TApi>,\n mockFactory: () => jest.Mocked<TApi>,\n): (partialImpl?: Partial<TApi>) => ApiMock<TApi> {\n return partialImpl => {\n const mock = mockFactory();\n if (partialImpl) {\n for (const [key, impl] of Object.entries(partialImpl)) {\n if (typeof impl === 'function') {\n (mock as any)[key].mockImplementation(impl);\n } else {\n (mock as any)[key] = impl;\n }\n }\n }\n return Object.assign(mock, {\n factory: createApiFactory({\n api: ref,\n deps: {},\n factory: () => mock,\n }),\n }) as ApiMock<TApi>;\n };\n}\n\n/**\n * Mock implementations of the core utility APIs, to be used in tests.\n *\n * @public\n * @remarks\n *\n * There are some variations among the APIs depending on what needs tests\n * might have, but overall there are three main usage patterns:\n *\n * 1: Creating an actual fake API instance, often with a simplified version\n * of functionality, by calling the mock API itself as a function.\n *\n * ```ts\n * // The function often accepts parameters that control its behavior\n * const foo = mockApis.foo();\n * ```\n *\n * 2: Creating a mock API, where all methods are replaced with jest mocks, by\n * calling the API's `mock` function.\n *\n * ```ts\n * // You can optionally supply a subset of its methods to implement\n * const foo = mockApis.foo.mock({\n * someMethod: () => 'mocked result',\n * });\n * // After exercising your test, you can make assertions on the mock:\n * expect(foo.someMethod).toHaveBeenCalledTimes(2);\n * expect(foo.otherMethod).toHaveBeenCalledWith(testData);\n * ```\n *\n * 3: Creating an API factory that behaves similarly to the mock as per above.\n *\n * ```ts\n * const factory = mockApis.foo.factory({\n * someMethod: () => 'mocked result',\n * });\n * ```\n */\nexport namespace mockApis {\n const analyticsMockSkeleton = (): jest.Mocked<AnalyticsApi> => ({\n captureEvent: jest.fn(),\n });\n /**\n * Mock implementation of {@link @backstage/core-plugin-api#AnalyticsApi}.\n *\n * @public\n */\n export function analytics(): AnalyticsApi {\n return analyticsMockSkeleton();\n }\n /**\n * Mock implementations of {@link @backstage/core-plugin-api#AnalyticsApi}.\n *\n * @public\n */\n export namespace analytics {\n export const factory = simpleFactory(analyticsApiRef, analytics);\n export const mock = simpleMock(analyticsApiRef, analyticsMockSkeleton);\n }\n\n /**\n * Fake implementation of {@link @backstage/core-plugin-api#ConfigApi}\n * with optional data supplied.\n *\n * @public\n * @example\n *\n * ```tsx\n * const config = mockApis.config({\n * data: { app: { baseUrl: 'https://example.com' } },\n * });\n *\n * await renderInTestApp(\n * <TestApiProvider apis={[[configApiRef, config]]}>\n * <MyTestedComponent />\n * </TestApiProvider>,\n * );\n * ```\n */\n export function config(options?: { data?: JsonObject }): ConfigApi {\n return new ConfigReader(options?.data, 'mock-config');\n }\n /**\n * Mock helpers for {@link @backstage/core-plugin-api#ConfigApi}.\n *\n * @see {@link @backstage/core-plugin-api#mockApis.config}\n * @public\n */\n export namespace config {\n /**\n * Creates a factory for a fake implementation of\n * {@link @backstage/core-plugin-api#ConfigApi} with optional\n * configuration data supplied.\n *\n * @public\n */\n export const factory = simpleFactory(configApiRef, config);\n /**\n * Creates a mock implementation of\n * {@link @backstage/core-plugin-api#ConfigApi}. All methods are\n * replaced with jest mock functions, and you can optionally pass in a\n * subset of methods with an explicit implementation.\n *\n * @public\n */\n export const mock = simpleMock(configApiRef, () => ({\n has: jest.fn(),\n keys: jest.fn(),\n get: jest.fn(),\n getOptional: jest.fn(),\n getConfig: jest.fn(),\n getOptionalConfig: jest.fn(),\n getConfigArray: jest.fn(),\n getOptionalConfigArray: jest.fn(),\n getNumber: jest.fn(),\n getOptionalNumber: jest.fn(),\n getBoolean: jest.fn(),\n getOptionalBoolean: jest.fn(),\n getString: jest.fn(),\n getOptionalString: jest.fn(),\n getStringArray: jest.fn(),\n getOptionalStringArray: jest.fn(),\n }));\n }\n\n /**\n * Fake implementation of {@link @backstage/core-plugin-api#DiscoveryApi}. By\n * default returns URLs on the form `http://example.com/api/<pluginIs>`.\n *\n * @public\n */\n export function discovery(options?: { baseUrl?: string }): DiscoveryApi {\n const baseUrl = options?.baseUrl ?? 'http://example.com';\n return {\n async getBaseUrl(pluginId: string) {\n return `${baseUrl}/api/${pluginId}`;\n },\n };\n }\n /**\n * Mock implementations of {@link @backstage/core-plugin-api#DiscoveryApi}.\n *\n * @public\n */\n export namespace discovery {\n export const factory = simpleFactory(discoveryApiRef, discovery);\n export const mock = simpleMock(discoveryApiRef, () => ({\n getBaseUrl: jest.fn(),\n }));\n }\n\n /**\n * Fake implementation of {@link @backstage/core-plugin-api#IdentityApi}. By\n * default returns no token or profile info, and the user `user:default/test`.\n *\n * @public\n */\n export function identity(options?: {\n userEntityRef?: string;\n ownershipEntityRefs?: string[];\n token?: string;\n email?: string;\n displayName?: string;\n picture?: string;\n }): IdentityApi {\n const {\n userEntityRef = 'user:default/test',\n ownershipEntityRefs = ['user:default/test'],\n token,\n email,\n displayName,\n picture,\n } = options ?? {};\n return {\n async getBackstageIdentity() {\n return { type: 'user', ownershipEntityRefs, userEntityRef };\n },\n async getCredentials() {\n return { token };\n },\n async getProfileInfo() {\n return { email, displayName, picture };\n },\n async signOut() {},\n };\n }\n /**\n * Mock implementations of {@link @backstage/core-plugin-api#IdentityApi}.\n *\n * @public\n */\n export namespace identity {\n export const factory = simpleFactory(identityApiRef, identity);\n export const mock = simpleMock(\n identityApiRef,\n (): jest.Mocked<IdentityApi> => ({\n getBackstageIdentity: jest.fn(),\n getCredentials: jest.fn(),\n getProfileInfo: jest.fn(),\n signOut: jest.fn(),\n }),\n );\n }\n\n /**\n * Fake implementation of\n * {@link @backstage/plugin-permission-react#PermissionApi}. By default allows\n * all actions.\n *\n * @public\n */\n export function permission(options?: {\n authorize?:\n | AuthorizeResult.ALLOW\n | AuthorizeResult.DENY\n | ((\n request: EvaluatePermissionRequest,\n ) => AuthorizeResult.ALLOW | AuthorizeResult.DENY);\n }): PermissionApi {\n const authorizeInput = options?.authorize;\n let authorize: (\n request: EvaluatePermissionRequest,\n ) => AuthorizeResult.ALLOW | AuthorizeResult.DENY;\n if (authorizeInput === undefined) {\n authorize = () => AuthorizeResult.ALLOW;\n } else if (typeof authorizeInput === 'function') {\n authorize = authorizeInput;\n } else {\n authorize = () => authorizeInput;\n }\n return new MockPermissionApi(authorize);\n }\n /**\n * Mock implementation of\n * {@link @backstage/plugin-permission-react#PermissionApi}.\n *\n * @public\n */\n export namespace permission {\n export const factory = simpleFactory(permissionApiRef, permission);\n export const mock = simpleMock(permissionApiRef, () => ({\n authorize: jest.fn(),\n }));\n }\n\n /**\n * Fake implementation of {@link @backstage/core-plugin-api#StorageApi}.\n * Stores data temporarily in memory.\n *\n * @public\n */\n export function storage(options?: { data?: JsonObject }): StorageApi {\n return MockStorageApi.create(options?.data);\n }\n /**\n * Mock implementations of {@link @backstage/core-plugin-api#StorageApi}.\n *\n * @public\n */\n export namespace storage {\n export const factory = simpleFactory(storageApiRef, storage);\n export const mock = simpleMock(storageApiRef, () => ({\n forBucket: jest.fn(),\n set: jest.fn(),\n remove: jest.fn(),\n observe$: jest.fn(),\n snapshot: jest.fn(),\n }));\n }\n\n /**\n * Fake implementation of {@link @backstage/core-plugin-api/alpha#TranslationApi}.\n * By default returns the default translation.\n *\n * @public\n */\n export function translation(): TranslationApi {\n return MockTranslationApi.create();\n }\n /**\n * Mock implementations of {@link @backstage/core-plugin-api/alpha#TranslationApi}.\n *\n * @public\n */\n export namespace translation {\n export const factory = simpleFactory(translationApiRef, translation);\n export const mock = simpleMock(translationApiRef, () => ({\n getTranslation: jest.fn(),\n translation$: jest.fn(),\n }));\n }\n}\n"],"names":["mockApis","analytics","config","discovery","identity","permission","storage","translation"],"mappings":";;;;;;;;;AAmDA,SAAS,aAAA,CACP,KACA,OACgD,EAAA;AAChD,EAAO,OAAA,CAAA,GAAI,SACT,gBAAiB,CAAA;AAAA,IACf,GAAK,EAAA,GAAA;AAAA,IACL,MAAM,EAAC;AAAA,IACP,OAAS,EAAA,MAAM,OAAQ,CAAA,GAAG,IAAI;AAAA,GAC/B,CAAA;AACL;AAGA,SAAS,UAAA,CACP,KACA,WACgD,EAAA;AAChD,EAAA,OAAO,CAAe,WAAA,KAAA;AACpB,IAAA,MAAM,OAAO,WAAY,EAAA;AACzB,IAAA,IAAI,WAAa,EAAA;AACf,MAAA,KAAA,MAAW,CAAC,GAAK,EAAA,IAAI,KAAK,MAAO,CAAA,OAAA,CAAQ,WAAW,CAAG,EAAA;AACrD,QAAI,IAAA,OAAO,SAAS,UAAY,EAAA;AAC9B,UAAC,IAAa,CAAA,GAAG,CAAE,CAAA,kBAAA,CAAmB,IAAI,CAAA;AAAA,SACrC,MAAA;AACL,UAAC,IAAA,CAAa,GAAG,CAAI,GAAA,IAAA;AAAA;AACvB;AACF;AAE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ClB,QAAA,EAAU,KAAK,EAAG;AAAA,KAClB,CAAA,CAAA;AAAA,GARa,EAAA,OAAA,GAAAN,SAAA,CAAA,OAAA,KAAAA,SAAA,CAAA,OAAA,GAAA,EAAA,CAAA,CAAA;AAiBV,EAAA,SAAS,WAA8B,GAAA;AAC5C,IAAA,OAAO,mBAAmB,MAAO,EAAA;AAAA;AAD5B,EAAAA,SAAS,CAAA,WAAA,GAAA,WAAA;AAQT,EAAA,CAAA,CAAUO,YAAV,KAAA;AACE,IAAMA,YAAA,CAAA,OAAA,GAAU,aAAc,CAAA,iBAAA,EAAmBA,YAAW,CAAA;AAC5D,IAAMA,YAAA,CAAA,IAAA,GAAO,UAAW,CAAA,iBAAA,EAAmB,OAAO;AAAA,MACvD,cAAA,EAAgB,KAAK,EAAG,EAAA;AAAA,MACxB,YAAA,EAAc,KAAK,EAAG;AAAA,KACtB,CAAA,CAAA;AAAA,GALa,EAAA,WAAA,GAAAP,SAAA,CAAA,WAAA,KAAAA,SAAA,CAAA,WAAA,GAAA,EAAA,CAAA,CAAA;AAAA,CAtPF,EAAA,QAAA,KAAA,QAAA,GAAA,EAAA,CAAA,CAAA;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"appWrappers.esm.js","sources":["../../src/testUtils/appWrappers.tsx"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport React, {\n ComponentType,\n PropsWithChildren,\n ReactElement,\n ReactNode,\n} from 'react';\nimport { MemoryRouter, Route } from 'react-router-dom';\nimport { themes, UnifiedThemeProvider } from '@backstage/theme';\nimport MockIcon from '@material-ui/icons/AcUnit';\nimport { AppIcons, createSpecializedApp } from '@backstage/core-app-api';\nimport {\n AppComponents,\n attachComponentData,\n BootErrorPageProps,\n createRouteRef,\n ExternalRouteRef,\n IconComponent,\n RouteRef,\n} from '@backstage/core-plugin-api';\nimport { MatcherFunction, RenderResult } from '@testing-library/react';\nimport { LegacyRootOption, renderWithEffects } from './testingLibrary';\nimport { defaultApis } from './defaultApis';\nimport { mockApis } from './mockApis';\n\nconst mockIcons = {\n 'kind:api': MockIcon,\n 'kind:component': MockIcon,\n 'kind:domain': MockIcon,\n 'kind:group': MockIcon,\n 'kind:location': MockIcon,\n 'kind:system': MockIcon,\n 'kind:user': MockIcon,\n 'kind:resource': MockIcon,\n 'kind:template': MockIcon,\n\n brokenImage: MockIcon,\n catalog: MockIcon,\n scaffolder: MockIcon,\n techdocs: MockIcon,\n search: MockIcon,\n chat: MockIcon,\n dashboard: MockIcon,\n docs: MockIcon,\n email: MockIcon,\n github: MockIcon,\n group: MockIcon,\n help: MockIcon,\n user: MockIcon,\n warning: MockIcon,\n star: MockIcon,\n unstarred: MockIcon,\n};\n\nconst ErrorBoundaryFallback = ({ error }: { error: Error }) => {\n throw new Error(`Reached ErrorBoundaryFallback Page with error, ${error}`);\n};\nconst NotFoundErrorPage = () => {\n throw new Error('Reached NotFound Page');\n};\nconst BootErrorPage = ({ step, error }: BootErrorPageProps) => {\n throw new Error(`Reached BootError Page at step ${step} with error ${error}`);\n};\nconst Progress = () => <div data-testid=\"progress\" />;\n\nconst NoRender = (_props: { children: ReactNode }) => null;\n\n/**\n * Options to customize the behavior of the test app wrapper.\n * @public\n */\nexport type TestAppOptions = {\n /**\n * Initial route entries to pass along as `initialEntries` to the router.\n */\n routeEntries?: string[];\n\n /**\n * An object of paths to mount route ref on, with the key being the path and the value\n * being the RouteRef that the path will be bound to. This allows the route refs to be\n * used by `useRouteRef` in the rendered elements.\n *\n * @example\n * wrapInTestApp(<MyComponent />, \\{\n * mountedRoutes: \\{\n * '/my-path': myRouteRef,\n * \\}\n * \\})\n * // ...\n * const link = useRouteRef(myRouteRef)\n */\n mountedRoutes?: { [path: string]: RouteRef | ExternalRouteRef };\n\n /**\n * Components to be forwarded to the `components` option of `createApp`.\n */\n components?: Partial<AppComponents>;\n\n /**\n * Icons to be forwarded to the `icons` option of `createApp`.\n */\n icons?: Partial<AppIcons> & {\n [key in string]: IconComponent;\n };\n};\n\nfunction isExternalRouteRef(\n routeRef: RouteRef | ExternalRouteRef,\n): routeRef is ExternalRouteRef {\n // TODO(Rugvip): Least ugly workaround for now, but replace :D\n return String(routeRef).includes('{type=external,');\n}\n\n/**\n * Creates a Wrapper component that wraps a component inside a Backstage test app,\n * providing a mocked theme and app context, along with mocked APIs.\n *\n * @param options - Additional options for the rendering.\n * @public\n */\nexport function createTestAppWrapper(\n options: TestAppOptions = {},\n): (props: { children: ReactNode }) => JSX.Element {\n const { routeEntries = ['/'] } = options;\n const boundRoutes = new Map<ExternalRouteRef, RouteRef>();\n\n const app = createSpecializedApp({\n apis: mockApis,\n defaultApis,\n // Bit of a hack to make sure that the default config loader isn't used\n // as that would force every single test to wait for config loading.\n configLoader: false as unknown as undefined,\n components: {\n Progress,\n BootErrorPage,\n NotFoundErrorPage,\n ErrorBoundaryFallback,\n Router: ({ children }) => (\n <MemoryRouter initialEntries={routeEntries} children={children} />\n ),\n ...options.components,\n },\n icons: {\n ...mockIcons,\n ...options.icons,\n },\n plugins: [],\n themes: [\n {\n id: 'light',\n title: 'Test App Theme',\n variant: 'light',\n Provider: ({ children }) => (\n <UnifiedThemeProvider theme={themes.light}>\n {children}\n </UnifiedThemeProvider>\n ),\n },\n ],\n bindRoutes: ({ bind }) => {\n for (const [externalRef, absoluteRef] of boundRoutes) {\n bind(\n { ref: externalRef },\n {\n ref: absoluteRef,\n },\n );\n }\n },\n });\n\n const routeElements = Object.entries(options.mountedRoutes ?? {}).map(\n ([path, routeRef]) => {\n const Page = () => <div>Mounted at {path}</div>;\n\n // Allow external route refs to be bound to paths as well, for convenience.\n // We work around it by creating and binding an absolute ref to the external one.\n if (isExternalRouteRef(routeRef)) {\n const absoluteRef = createRouteRef({ id: 'id' });\n boundRoutes.set(routeRef, absoluteRef);\n attachComponentData(Page, 'core.mountPoint', absoluteRef);\n } else {\n attachComponentData(Page, 'core.mountPoint', routeRef);\n }\n return <Route key={path} path={path} element={<Page />} />;\n },\n );\n\n const AppProvider = app.getProvider();\n const AppRouter = app.getRouter();\n\n const TestAppWrapper = ({ children }: { children: ReactNode }) => (\n <AppProvider>\n <AppRouter>\n <NoRender>{routeElements}</NoRender>\n {children}\n </AppRouter>\n </AppProvider>\n );\n\n return TestAppWrapper;\n}\n\n/**\n * Wraps a component inside a Backstage test app, providing a mocked theme\n * and app context, along with mocked APIs.\n *\n * @param Component - A component or react node to render inside the test app.\n * @param options - Additional options for the rendering.\n * @public\n */\nexport function wrapInTestApp(\n Component: ComponentType | ReactNode,\n options: TestAppOptions = {},\n): ReactElement {\n const TestAppWrapper = createTestAppWrapper(options);\n\n let wrappedElement: React.ReactElement;\n if (Component instanceof Function) {\n wrappedElement = React.createElement(Component as ComponentType);\n } else {\n wrappedElement = Component as React.ReactElement;\n }\n\n return <TestAppWrapper>{wrappedElement}</TestAppWrapper>;\n}\n\n/**\n * Renders a component inside a Backstage test app, providing a mocked theme\n * and app context, along with mocked APIs.\n *\n * The render executes async effects similar to `renderWithEffects`. To avoid this\n * behavior, use a regular `render()` + `wrapInTestApp()` instead.\n *\n * @param Component - A component or react node to render inside the test app.\n * @param options - Additional options for the rendering.\n * @public\n */\nexport async function renderInTestApp(\n Component: ComponentType<PropsWithChildren<{}>> | ReactNode,\n options: TestAppOptions & LegacyRootOption = {},\n): Promise<RenderResult> {\n let wrappedElement: React.ReactElement;\n if (Component instanceof Function) {\n wrappedElement = React.createElement(Component as ComponentType);\n } else {\n wrappedElement = Component as React.ReactElement;\n }\n const { legacyRoot } = options;\n\n return renderWithEffects(wrappedElement, {\n wrapper: createTestAppWrapper(options),\n legacyRoot,\n });\n}\n\n/**\n * Returns a `@testing-library/react` valid MatcherFunction for supplied text\n *\n * @param string - text Text to match by element's textContent\n *\n * @public\n */\nexport const textContentMatcher =\n (text: string): MatcherFunction =>\n (_, node) => {\n if (!node) {\n return false;\n }\n\n const hasText = (textNode: Element) =>\n textNode?.textContent?.includes(text) ?? false;\n const childrenDontHaveText = (containerNode: Element) =>\n Array.from(containerNode?.children).every(child => !hasText(child));\n\n return hasText(node) && childrenDontHaveText(node);\n };\n"],"names":[],"mappings":";;;;;;;;;;AAwCA,MAAM,SAAY,GAAA;AAAA,EAChB,UAAY,EAAA,QAAA;AAAA,EACZ,gBAAkB,EAAA,QAAA;AAAA,EAClB,aAAe,EAAA,QAAA;AAAA,EACf,YAAc,EAAA,QAAA;AAAA,EACd,eAAiB,EAAA,QAAA;AAAA,EACjB,aAAe,EAAA,QAAA;AAAA,EACf,WAAa,EAAA,QAAA;AAAA,EACb,eAAiB,EAAA,QAAA;AAAA,EACjB,eAAiB,EAAA,QAAA;AAAA,EAEjB,WAAa,EAAA,QAAA;AAAA,EACb,OAAS,EAAA,QAAA;AAAA,EACT,UAAY,EAAA,QAAA;AAAA,EACZ,QAAU,EAAA,QAAA;AAAA,EACV,MAAQ,EAAA,QAAA;AAAA,EACR,IAAM,EAAA,QAAA;AAAA,EACN,SAAW,EAAA,QAAA;AAAA,EACX,IAAM,EAAA,QAAA;AAAA,EACN,KAAO,EAAA,QAAA;AAAA,EACP,MAAQ,EAAA,QAAA;AAAA,EACR,KAAO,EAAA,QAAA;AAAA,EACP,IAAM,EAAA,QAAA;AAAA,EACN,IAAM,EAAA,QAAA;AAAA,EACN,OAAS,EAAA,QAAA;AAAA,EACT,IAAM,EAAA,QAAA;AAAA,EACN,SAAW,EAAA,QAAA;AACb,CAAA,CAAA;AAEA,MAAM,qBAAwB,GAAA,CAAC,EAAE,KAAA,EAA8B,KAAA;AAC7D,EAAA,MAAM,IAAI,KAAA,CAAM,CAAk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iB,cAAA,GAAA,SAAA,CAAA;AAAA,GACnB;AACA,EAAM,MAAA,EAAE,YAAe,GAAA,OAAA,CAAA;AAEvB,EAAA,OAAO,kBAAkB,cAAgB,EAAA;AAAA,IACvC,OAAA,EAAS,qBAAqB,OAAO,CAAA;AAAA,IACrC,UAAA;AAAA,GACD,CAAA,CAAA;AACH,CAAA;AASO,MAAM,kBACX,GAAA,CAAC,IACD,KAAA,CAAC,GAAG,IAAS,KAAA;AACX,EAAA,IAAI,CAAC,IAAM,EAAA;AACT,IAAO,OAAA,KAAA,CAAA;AAAA,GACT;AAEA,EAAA,MAAM,UAAU,CAAC,QAAA,KACf,UAAU,WAAa,EAAA,QAAA,CAAS,IAAI,CAAK,IAAA,KAAA,CAAA;AAC3C,EAAA,MAAM,oBAAuB,GAAA,CAAC,aAC5B,KAAA,KAAA,CAAM,IAAK,CAAA,aAAA,EAAe,QAAQ,CAAA,CAAE,KAAM,CAAA,CAAA,KAAA,KAAS,CAAC,OAAA,CAAQ,KAAK,CAAC,CAAA,CAAA;AAEpE,EAAA,OAAO,OAAQ,CAAA,IAAI,CAAK,IAAA,oBAAA,CAAqB,IAAI,CAAA,CAAA;AACnD;;;;"}
|
|
1
|
+
{"version":3,"file":"appWrappers.esm.js","sources":["../../src/testUtils/appWrappers.tsx"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport React, {\n ComponentType,\n PropsWithChildren,\n ReactElement,\n ReactNode,\n} from 'react';\nimport { MemoryRouter, Route } from 'react-router-dom';\nimport { themes, UnifiedThemeProvider } from '@backstage/theme';\nimport MockIcon from '@material-ui/icons/AcUnit';\nimport { AppIcons, createSpecializedApp } from '@backstage/core-app-api';\nimport {\n AppComponents,\n attachComponentData,\n BootErrorPageProps,\n createRouteRef,\n ExternalRouteRef,\n IconComponent,\n RouteRef,\n} from '@backstage/core-plugin-api';\nimport { MatcherFunction, RenderResult } from '@testing-library/react';\nimport { LegacyRootOption, renderWithEffects } from './testingLibrary';\nimport { defaultApis } from './defaultApis';\nimport { mockApis } from './mockApis';\n\nconst mockIcons = {\n 'kind:api': MockIcon,\n 'kind:component': MockIcon,\n 'kind:domain': MockIcon,\n 'kind:group': MockIcon,\n 'kind:location': MockIcon,\n 'kind:system': MockIcon,\n 'kind:user': MockIcon,\n 'kind:resource': MockIcon,\n 'kind:template': MockIcon,\n\n brokenImage: MockIcon,\n catalog: MockIcon,\n scaffolder: MockIcon,\n techdocs: MockIcon,\n search: MockIcon,\n chat: MockIcon,\n dashboard: MockIcon,\n docs: MockIcon,\n email: MockIcon,\n github: MockIcon,\n group: MockIcon,\n help: MockIcon,\n user: MockIcon,\n warning: MockIcon,\n star: MockIcon,\n unstarred: MockIcon,\n};\n\nconst ErrorBoundaryFallback = ({ error }: { error: Error }) => {\n throw new Error(`Reached ErrorBoundaryFallback Page with error, ${error}`);\n};\nconst NotFoundErrorPage = () => {\n throw new Error('Reached NotFound Page');\n};\nconst BootErrorPage = ({ step, error }: BootErrorPageProps) => {\n throw new Error(`Reached BootError Page at step ${step} with error ${error}`);\n};\nconst Progress = () => <div data-testid=\"progress\" />;\n\nconst NoRender = (_props: { children: ReactNode }) => null;\n\n/**\n * Options to customize the behavior of the test app wrapper.\n * @public\n */\nexport type TestAppOptions = {\n /**\n * Initial route entries to pass along as `initialEntries` to the router.\n */\n routeEntries?: string[];\n\n /**\n * An object of paths to mount route ref on, with the key being the path and the value\n * being the RouteRef that the path will be bound to. This allows the route refs to be\n * used by `useRouteRef` in the rendered elements.\n *\n * @example\n * wrapInTestApp(<MyComponent />, \\{\n * mountedRoutes: \\{\n * '/my-path': myRouteRef,\n * \\}\n * \\})\n * // ...\n * const link = useRouteRef(myRouteRef)\n */\n mountedRoutes?: { [path: string]: RouteRef | ExternalRouteRef };\n\n /**\n * Components to be forwarded to the `components` option of `createApp`.\n */\n components?: Partial<AppComponents>;\n\n /**\n * Icons to be forwarded to the `icons` option of `createApp`.\n */\n icons?: Partial<AppIcons> & {\n [key in string]: IconComponent;\n };\n};\n\nfunction isExternalRouteRef(\n routeRef: RouteRef | ExternalRouteRef,\n): routeRef is ExternalRouteRef {\n // TODO(Rugvip): Least ugly workaround for now, but replace :D\n return String(routeRef).includes('{type=external,');\n}\n\n/**\n * Creates a Wrapper component that wraps a component inside a Backstage test app,\n * providing a mocked theme and app context, along with mocked APIs.\n *\n * @param options - Additional options for the rendering.\n * @public\n */\nexport function createTestAppWrapper(\n options: TestAppOptions = {},\n): (props: { children: ReactNode }) => JSX.Element {\n const { routeEntries = ['/'] } = options;\n const boundRoutes = new Map<ExternalRouteRef, RouteRef>();\n\n const app = createSpecializedApp({\n apis: mockApis,\n defaultApis,\n // Bit of a hack to make sure that the default config loader isn't used\n // as that would force every single test to wait for config loading.\n configLoader: false as unknown as undefined,\n components: {\n Progress,\n BootErrorPage,\n NotFoundErrorPage,\n ErrorBoundaryFallback,\n Router: ({ children }) => (\n <MemoryRouter initialEntries={routeEntries} children={children} />\n ),\n ...options.components,\n },\n icons: {\n ...mockIcons,\n ...options.icons,\n },\n plugins: [],\n themes: [\n {\n id: 'light',\n title: 'Test App Theme',\n variant: 'light',\n Provider: ({ children }) => (\n <UnifiedThemeProvider theme={themes.light}>\n {children}\n </UnifiedThemeProvider>\n ),\n },\n ],\n bindRoutes: ({ bind }) => {\n for (const [externalRef, absoluteRef] of boundRoutes) {\n bind(\n { ref: externalRef },\n {\n ref: absoluteRef,\n },\n );\n }\n },\n });\n\n const routeElements = Object.entries(options.mountedRoutes ?? {}).map(\n ([path, routeRef]) => {\n const Page = () => <div>Mounted at {path}</div>;\n\n // Allow external route refs to be bound to paths as well, for convenience.\n // We work around it by creating and binding an absolute ref to the external one.\n if (isExternalRouteRef(routeRef)) {\n const absoluteRef = createRouteRef({ id: 'id' });\n boundRoutes.set(routeRef, absoluteRef);\n attachComponentData(Page, 'core.mountPoint', absoluteRef);\n } else {\n attachComponentData(Page, 'core.mountPoint', routeRef);\n }\n return <Route key={path} path={path} element={<Page />} />;\n },\n );\n\n const AppProvider = app.getProvider();\n const AppRouter = app.getRouter();\n\n const TestAppWrapper = ({ children }: { children: ReactNode }) => (\n <AppProvider>\n <AppRouter>\n <NoRender>{routeElements}</NoRender>\n {children}\n </AppRouter>\n </AppProvider>\n );\n\n return TestAppWrapper;\n}\n\n/**\n * Wraps a component inside a Backstage test app, providing a mocked theme\n * and app context, along with mocked APIs.\n *\n * @param Component - A component or react node to render inside the test app.\n * @param options - Additional options for the rendering.\n * @public\n */\nexport function wrapInTestApp(\n Component: ComponentType | ReactNode,\n options: TestAppOptions = {},\n): ReactElement {\n const TestAppWrapper = createTestAppWrapper(options);\n\n let wrappedElement: React.ReactElement;\n if (Component instanceof Function) {\n wrappedElement = React.createElement(Component as ComponentType);\n } else {\n wrappedElement = Component as React.ReactElement;\n }\n\n return <TestAppWrapper>{wrappedElement}</TestAppWrapper>;\n}\n\n/**\n * Renders a component inside a Backstage test app, providing a mocked theme\n * and app context, along with mocked APIs.\n *\n * The render executes async effects similar to `renderWithEffects`. To avoid this\n * behavior, use a regular `render()` + `wrapInTestApp()` instead.\n *\n * @param Component - A component or react node to render inside the test app.\n * @param options - Additional options for the rendering.\n * @public\n */\nexport async function renderInTestApp(\n Component: ComponentType<PropsWithChildren<{}>> | ReactNode,\n options: TestAppOptions & LegacyRootOption = {},\n): Promise<RenderResult> {\n let wrappedElement: React.ReactElement;\n if (Component instanceof Function) {\n wrappedElement = React.createElement(Component as ComponentType);\n } else {\n wrappedElement = Component as React.ReactElement;\n }\n const { legacyRoot } = options;\n\n return renderWithEffects(wrappedElement, {\n wrapper: createTestAppWrapper(options),\n legacyRoot,\n });\n}\n\n/**\n * Returns a `@testing-library/react` valid MatcherFunction for supplied text\n *\n * @param string - text Text to match by element's textContent\n *\n * @public\n */\nexport const textContentMatcher =\n (text: string): MatcherFunction =>\n (_, node) => {\n if (!node) {\n return false;\n }\n\n const hasText = (textNode: Element) =>\n textNode?.textContent?.includes(text) ?? false;\n const childrenDontHaveText = (containerNode: Element) =>\n Array.from(containerNode?.children).every(child => !hasText(child));\n\n return hasText(node) && childrenDontHaveText(node);\n };\n"],"names":[],"mappings":";;;;;;;;;;AAwCA,MAAM,SAAY,GAAA;AAAA,EAChB,UAAY,EAAA,QAAA;AAAA,EACZ,gBAAkB,EAAA,QAAA;AAAA,EAClB,aAAe,EAAA,QAAA;AAAA,EACf,YAAc,EAAA,QAAA;AAAA,EACd,eAAiB,EAAA,QAAA;AAAA,EACjB,aAAe,EAAA,QAAA;AAAA,EACf,WAAa,EAAA,QAAA;AAAA,EACb,eAAiB,EAAA,QAAA;AAAA,EACjB,eAAiB,EAAA,QAAA;AAAA,EAEjB,WAAa,EAAA,QAAA;AAAA,EACb,OAAS,EAAA,QAAA;AAAA,EACT,UAAY,EAAA,QAAA;AAAA,EACZ,QAAU,EAAA,QAAA;AAAA,EACV,MAAQ,EAAA,QAAA;AAAA,EACR,IAAM,EAAA,QAAA;AAAA,EACN,SAAW,EAAA,QAAA;AAAA,EACX,IAAM,EAAA,QAAA;AAAA,EACN,KAAO,EAAA,QAAA;AAAA,EACP,MAAQ,EAAA,QAAA;AAAA,EACR,KAAO,EAAA,QAAA;AAAA,EACP,IAAM,EAAA,QAAA;AAAA,EACN,IAAM,EAAA,QAAA;AAAA,EACN,OAAS,EAAA,QAAA;AAAA,EACT,IAAM,EAAA,QAAA;AAAA,EACN,SAAW,EAAA;AACb,CAAA;AAEA,MAAM,qBAAwB,GAAA,CAAC,EAAE,KAAA,EAA8B,KAAA;AAC7D,EAAA,MAAM,IAAI,KAAA,CAAM,CAAkD,+CAAA,EAAA,KA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AA;AACT,IAAO,OAAA,KAAA;AAAA;AAGT,EAAA,MAAM,UAAU,CAAC,QAAA,KACf,UAAU,WAAa,EAAA,QAAA,CAAS,IAAI,CAAK,IAAA,KAAA;AAC3C,EAAA,MAAM,oBAAuB,GAAA,CAAC,aAC5B,KAAA,KAAA,CAAM,IAAK,CAAA,aAAA,EAAe,QAAQ,CAAA,CAAE,KAAM,CAAA,CAAA,KAAA,KAAS,CAAC,OAAA,CAAQ,KAAK,CAAC,CAAA;AAEpE,EAAA,OAAO,OAAQ,CAAA,IAAI,CAAK,IAAA,oBAAA,CAAqB,IAAI,CAAA;AACnD;;;;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { UrlPatternDiscovery, AlertApiForwarder, NoOpAnalyticsApi, ErrorAlerter, ErrorApiForwarder, UnhandledErrorForwarder, WebStorage, OAuthRequestManager, GoogleAuth, MicrosoftAuth, GithubAuth, OktaAuth, GitlabAuth, OneLoginAuth, BitbucketAuth, AtlassianAuth } from '@backstage/core-app-api';
|
|
2
|
-
import { createApiFactory,
|
|
2
|
+
import { createApiFactory, configApiRef, discoveryApiRef, alertApiRef, analyticsApiRef, errorApiRef, storageApiRef, oauthRequestApiRef, googleAuthApiRef, microsoftAuthApiRef, githubAuthApiRef, oktaAuthApiRef, gitlabAuthApiRef, oneloginAuthApiRef, bitbucketAuthApiRef, atlassianAuthApiRef } from '@backstage/core-plugin-api';
|
|
3
3
|
|
|
4
4
|
const defaultApis = [
|
|
5
5
|
createApiFactory({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"defaultApis.esm.js","sources":["../../src/testUtils/defaultApis.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AlertApiForwarder,\n NoOpAnalyticsApi,\n ErrorApiForwarder,\n ErrorAlerter,\n GoogleAuth,\n GithubAuth,\n OktaAuth,\n GitlabAuth,\n MicrosoftAuth,\n BitbucketAuth,\n OAuthRequestManager,\n WebStorage,\n UrlPatternDiscovery,\n OneLoginAuth,\n UnhandledErrorForwarder,\n AtlassianAuth,\n} from '@backstage/core-app-api';\n\nimport {\n createApiFactory,\n alertApiRef,\n analyticsApiRef,\n errorApiRef,\n discoveryApiRef,\n oauthRequestApiRef,\n googleAuthApiRef,\n githubAuthApiRef,\n oktaAuthApiRef,\n gitlabAuthApiRef,\n microsoftAuthApiRef,\n storageApiRef,\n configApiRef,\n oneloginAuthApiRef,\n bitbucketAuthApiRef,\n atlassianAuthApiRef,\n} from '@backstage/core-plugin-api';\n\n// TODO(Rugvip): This is just a copy of the createApp default APIs for now, but\n// we should clean up this list a bit move more things over to mocks.\nexport const defaultApis = [\n createApiFactory({\n api: discoveryApiRef,\n deps: { configApi: configApiRef },\n factory: ({ configApi }) =>\n UrlPatternDiscovery.compile(\n `${configApi.getString('backend.baseUrl')}/api/{{ pluginId }}`,\n ),\n }),\n createApiFactory(alertApiRef, new AlertApiForwarder()),\n createApiFactory(analyticsApiRef, new NoOpAnalyticsApi()),\n createApiFactory({\n api: errorApiRef,\n deps: { alertApi: alertApiRef },\n factory: ({ alertApi }) => {\n const errorApi = new ErrorAlerter(alertApi, new ErrorApiForwarder());\n UnhandledErrorForwarder.forward(errorApi, { hidden: false });\n return errorApi;\n },\n }),\n createApiFactory({\n api: storageApiRef,\n deps: { errorApi: errorApiRef },\n factory: ({ errorApi }) => WebStorage.create({ errorApi }),\n }),\n createApiFactory(oauthRequestApiRef, new OAuthRequestManager()),\n createApiFactory({\n api: googleAuthApiRef,\n deps: {\n discoveryApi: discoveryApiRef,\n oauthRequestApi: oauthRequestApiRef,\n configApi: configApiRef,\n },\n factory: ({ discoveryApi, oauthRequestApi, configApi }) =>\n GoogleAuth.create({\n configApi,\n discoveryApi,\n oauthRequestApi,\n environment: configApi.getOptionalString('auth.environment'),\n }),\n }),\n createApiFactory({\n api: microsoftAuthApiRef,\n deps: {\n discoveryApi: discoveryApiRef,\n oauthRequestApi: oauthRequestApiRef,\n configApi: configApiRef,\n },\n factory: ({ discoveryApi, oauthRequestApi, configApi }) =>\n MicrosoftAuth.create({\n configApi,\n discoveryApi,\n oauthRequestApi,\n environment: configApi.getOptionalString('auth.environment'),\n }),\n }),\n createApiFactory({\n api: githubAuthApiRef,\n deps: {\n discoveryApi: discoveryApiRef,\n oauthRequestApi: oauthRequestApiRef,\n configApi: configApiRef,\n },\n factory: ({ discoveryApi, oauthRequestApi, configApi }) =>\n GithubAuth.create({\n configApi,\n discoveryApi,\n oauthRequestApi,\n defaultScopes: ['read:user'],\n environment: configApi.getOptionalString('auth.environment'),\n }),\n }),\n createApiFactory({\n api: oktaAuthApiRef,\n deps: {\n discoveryApi: discoveryApiRef,\n oauthRequestApi: oauthRequestApiRef,\n configApi: configApiRef,\n },\n factory: ({ discoveryApi, oauthRequestApi, configApi }) =>\n OktaAuth.create({\n configApi,\n discoveryApi,\n oauthRequestApi,\n environment: configApi.getOptionalString('auth.environment'),\n }),\n }),\n createApiFactory({\n api: gitlabAuthApiRef,\n deps: {\n discoveryApi: discoveryApiRef,\n oauthRequestApi: oauthRequestApiRef,\n configApi: configApiRef,\n },\n factory: ({ discoveryApi, oauthRequestApi, configApi }) =>\n GitlabAuth.create({\n configApi,\n discoveryApi,\n oauthRequestApi,\n environment: configApi.getOptionalString('auth.environment'),\n }),\n }),\n createApiFactory({\n api: oneloginAuthApiRef,\n deps: {\n discoveryApi: discoveryApiRef,\n oauthRequestApi: oauthRequestApiRef,\n configApi: configApiRef,\n },\n factory: ({ discoveryApi, oauthRequestApi, configApi }) =>\n OneLoginAuth.create({\n configApi,\n discoveryApi,\n oauthRequestApi,\n environment: configApi.getOptionalString('auth.environment'),\n }),\n }),\n createApiFactory({\n api: bitbucketAuthApiRef,\n deps: {\n discoveryApi: discoveryApiRef,\n oauthRequestApi: oauthRequestApiRef,\n configApi: configApiRef,\n },\n factory: ({ discoveryApi, oauthRequestApi, configApi }) =>\n BitbucketAuth.create({\n configApi,\n discoveryApi,\n oauthRequestApi,\n defaultScopes: ['account'],\n environment: configApi.getOptionalString('auth.environment'),\n }),\n }),\n createApiFactory({\n api: atlassianAuthApiRef,\n deps: {\n discoveryApi: discoveryApiRef,\n oauthRequestApi: oauthRequestApiRef,\n configApi: configApiRef,\n },\n factory: ({ discoveryApi, oauthRequestApi, configApi }) => {\n return AtlassianAuth.create({\n configApi,\n discoveryApi,\n oauthRequestApi,\n environment: configApi.getOptionalString('auth.environment'),\n });\n },\n }),\n];\n"],"names":[],"mappings":";;;AAwDO,MAAM,WAAc,GAAA;AAAA,EACzB,gBAAiB,CAAA;AAAA,IACf,GAAK,EAAA,eAAA;AAAA,IACL,IAAA,EAAM,EAAE,SAAA,EAAW,YAAa,EAAA;AAAA,IAChC,OAAS,EAAA,CAAC,EAAE,SAAA,OACV,mBAAoB,CAAA,OAAA;AAAA,MAClB,CAAG,EAAA,SAAA,CAAU,SAAU,CAAA,iBAAiB,CAAC,CAAA,mBAAA,CAAA;AAAA,KAC3C;AAAA,GACH,CAAA;AAAA,EACD,gBAAiB,CAAA,WAAA,EAAa,IAAI,iBAAA,EAAmB,CAAA;AAAA,EACrD,gBAAiB,CAAA,eAAA,EAAiB,IAAI,gBAAA,EAAkB,CAAA;AAAA,EACxD,gBAAiB,CAAA;AAAA,IACf,GAAK,EAAA,WAAA;AAAA,IACL,IAAA,EAAM,EAAE,QAAA,EAAU,WAAY,EAAA;AAAA,IAC9B,OAAS,EAAA,CAAC,EAAE,QAAA,EAAe,KAAA;AACzB,MAAA,MAAM,WAAW,IAAI,YAAA,CAAa,QAAU,EAAA,IAAI,mBAAmB,CAAA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AAS,CAAC,EAAE,YAAc,EAAA,eAAA,EAAiB,WAAgB,KAAA;AACzD,MAAA,OAAO,cAAc,MAAO,CAAA;AAAA,QAC1B,SAAA;AAAA,QACA,YAAA;AAAA,QACA,eAAA;AAAA,QACA,WAAA,EAAa,SAAU,CAAA,iBAAA,CAAkB,kBAAkB,CAAA;AAAA,OAC5D,CAAA,CAAA;AAAA,KACH;AAAA,GACD,CAAA;AACH;;;;"}
|
|
1
|
+
{"version":3,"file":"defaultApis.esm.js","sources":["../../src/testUtils/defaultApis.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n AlertApiForwarder,\n NoOpAnalyticsApi,\n ErrorApiForwarder,\n ErrorAlerter,\n GoogleAuth,\n GithubAuth,\n OktaAuth,\n GitlabAuth,\n MicrosoftAuth,\n BitbucketAuth,\n OAuthRequestManager,\n WebStorage,\n UrlPatternDiscovery,\n OneLoginAuth,\n UnhandledErrorForwarder,\n AtlassianAuth,\n} from '@backstage/core-app-api';\n\nimport {\n createApiFactory,\n alertApiRef,\n analyticsApiRef,\n errorApiRef,\n discoveryApiRef,\n oauthRequestApiRef,\n googleAuthApiRef,\n githubAuthApiRef,\n oktaAuthApiRef,\n gitlabAuthApiRef,\n microsoftAuthApiRef,\n storageApiRef,\n configApiRef,\n oneloginAuthApiRef,\n bitbucketAuthApiRef,\n atlassianAuthApiRef,\n} from '@backstage/core-plugin-api';\n\n// TODO(Rugvip): This is just a copy of the createApp default APIs for now, but\n// we should clean up this list a bit move more things over to mocks.\nexport const defaultApis = [\n createApiFactory({\n api: discoveryApiRef,\n deps: { configApi: configApiRef },\n factory: ({ configApi }) =>\n UrlPatternDiscovery.compile(\n `${configApi.getString('backend.baseUrl')}/api/{{ pluginId }}`,\n ),\n }),\n createApiFactory(alertApiRef, new AlertApiForwarder()),\n createApiFactory(analyticsApiRef, new NoOpAnalyticsApi()),\n createApiFactory({\n api: errorApiRef,\n deps: { alertApi: alertApiRef },\n factory: ({ alertApi }) => {\n const errorApi = new ErrorAlerter(alertApi, new ErrorApiForwarder());\n UnhandledErrorForwarder.forward(errorApi, { hidden: false });\n return errorApi;\n },\n }),\n createApiFactory({\n api: storageApiRef,\n deps: { errorApi: errorApiRef },\n factory: ({ errorApi }) => WebStorage.create({ errorApi }),\n }),\n createApiFactory(oauthRequestApiRef, new OAuthRequestManager()),\n createApiFactory({\n api: googleAuthApiRef,\n deps: {\n discoveryApi: discoveryApiRef,\n oauthRequestApi: oauthRequestApiRef,\n configApi: configApiRef,\n },\n factory: ({ discoveryApi, oauthRequestApi, configApi }) =>\n GoogleAuth.create({\n configApi,\n discoveryApi,\n oauthRequestApi,\n environment: configApi.getOptionalString('auth.environment'),\n }),\n }),\n createApiFactory({\n api: microsoftAuthApiRef,\n deps: {\n discoveryApi: discoveryApiRef,\n oauthRequestApi: oauthRequestApiRef,\n configApi: configApiRef,\n },\n factory: ({ discoveryApi, oauthRequestApi, configApi }) =>\n MicrosoftAuth.create({\n configApi,\n discoveryApi,\n oauthRequestApi,\n environment: configApi.getOptionalString('auth.environment'),\n }),\n }),\n createApiFactory({\n api: githubAuthApiRef,\n deps: {\n discoveryApi: discoveryApiRef,\n oauthRequestApi: oauthRequestApiRef,\n configApi: configApiRef,\n },\n factory: ({ discoveryApi, oauthRequestApi, configApi }) =>\n GithubAuth.create({\n configApi,\n discoveryApi,\n oauthRequestApi,\n defaultScopes: ['read:user'],\n environment: configApi.getOptionalString('auth.environment'),\n }),\n }),\n createApiFactory({\n api: oktaAuthApiRef,\n deps: {\n discoveryApi: discoveryApiRef,\n oauthRequestApi: oauthRequestApiRef,\n configApi: configApiRef,\n },\n factory: ({ discoveryApi, oauthRequestApi, configApi }) =>\n OktaAuth.create({\n configApi,\n discoveryApi,\n oauthRequestApi,\n environment: configApi.getOptionalString('auth.environment'),\n }),\n }),\n createApiFactory({\n api: gitlabAuthApiRef,\n deps: {\n discoveryApi: discoveryApiRef,\n oauthRequestApi: oauthRequestApiRef,\n configApi: configApiRef,\n },\n factory: ({ discoveryApi, oauthRequestApi, configApi }) =>\n GitlabAuth.create({\n configApi,\n discoveryApi,\n oauthRequestApi,\n environment: configApi.getOptionalString('auth.environment'),\n }),\n }),\n createApiFactory({\n api: oneloginAuthApiRef,\n deps: {\n discoveryApi: discoveryApiRef,\n oauthRequestApi: oauthRequestApiRef,\n configApi: configApiRef,\n },\n factory: ({ discoveryApi, oauthRequestApi, configApi }) =>\n OneLoginAuth.create({\n configApi,\n discoveryApi,\n oauthRequestApi,\n environment: configApi.getOptionalString('auth.environment'),\n }),\n }),\n createApiFactory({\n api: bitbucketAuthApiRef,\n deps: {\n discoveryApi: discoveryApiRef,\n oauthRequestApi: oauthRequestApiRef,\n configApi: configApiRef,\n },\n factory: ({ discoveryApi, oauthRequestApi, configApi }) =>\n BitbucketAuth.create({\n configApi,\n discoveryApi,\n oauthRequestApi,\n defaultScopes: ['account'],\n environment: configApi.getOptionalString('auth.environment'),\n }),\n }),\n createApiFactory({\n api: atlassianAuthApiRef,\n deps: {\n discoveryApi: discoveryApiRef,\n oauthRequestApi: oauthRequestApiRef,\n configApi: configApiRef,\n },\n factory: ({ discoveryApi, oauthRequestApi, configApi }) => {\n return AtlassianAuth.create({\n configApi,\n discoveryApi,\n oauthRequestApi,\n environment: configApi.getOptionalString('auth.environment'),\n });\n },\n }),\n];\n"],"names":[],"mappings":";;;AAwDO,MAAM,WAAc,GAAA;AAAA,EACzB,gBAAiB,CAAA;AAAA,IACf,GAAK,EAAA,eAAA;AAAA,IACL,IAAA,EAAM,EAAE,SAAA,EAAW,YAAa,EA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CAAA;AAAA,MACnB,SAAA;AAAA,MACA,YAAA;AAAA,MACA,eAAA;AAAA,MACA,aAAA,EAAe,CAAC,SAAS,CAAA;AAAA,MACzB,WAAA,EAAa,SAAU,CAAA,iBAAA,CAAkB,kBAAkB;AAAA,KAC5D;AAAA,GACJ,CAAA;AAAA,EACD,gBAAiB,CAAA;AAAA,IACf,GAAK,EAAA,mBAAA;AAAA,IACL,IAAM,EAAA;AAAA,MACJ,YAAc,EAAA,eAAA;AAAA,MACd,eAAiB,EAAA,kBAAA;AAAA,MACjB,SAAW,EAAA;AAAA,KACb;AAAA,IACA,SAAS,CAAC,EAAE,YAAc,EAAA,eAAA,EAAiB,WAAgB,KAAA;AACzD,MAAA,OAAO,cAAc,MAAO,CAAA;AAAA,QAC1B,SAAA;AAAA,QACA,YAAA;AAAA,QACA,eAAA;AAAA,QACA,WAAA,EAAa,SAAU,CAAA,iBAAA,CAAkB,kBAAkB;AAAA,OAC5D,CAAA;AAAA;AACH,GACD;AACH;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logCollector.esm.js","sources":["../../src/testUtils/logCollector.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable no-console */\n\n/**\n * Severity levels of {@link CollectedLogs}\n * @public\n */\nexport type LogFuncs = 'log' | 'warn' | 'error';\n/**\n * AsyncLogCollector type used in {@link (withLogCollector:1)} callback function.\n * @public\n */\nexport type AsyncLogCollector = () => Promise<void>;\n/**\n * SyncLogCollector type used in {@link (withLogCollector:2)} callback function.\n * @public\n */\nexport type SyncLogCollector = () => void;\n/**\n * Union type used in {@link (withLogCollector:3)} callback function.\n * @public\n */\nexport type LogCollector = AsyncLogCollector | SyncLogCollector;\n/**\n * Map of severity level and corresponding log lines.\n * @public\n */\nexport type CollectedLogs<T extends LogFuncs> = { [key in T]: string[] };\n\nconst allCategories = ['log', 'warn', 'error'];\n\n/**\n * Asynchronous log collector with that collects all categories\n * @public\n */\nexport function withLogCollector(\n callback: AsyncLogCollector,\n): Promise<CollectedLogs<LogFuncs>>;\n\n/**\n * Synchronous log collector with that collects all categories\n * @public\n */\nexport function withLogCollector(\n callback: SyncLogCollector,\n): CollectedLogs<LogFuncs>;\n\n/**\n * Asynchronous log collector with that only collects selected categories\n * @public\n */\nexport function withLogCollector<T extends LogFuncs>(\n logsToCollect: T[],\n callback: AsyncLogCollector,\n): Promise<CollectedLogs<T>>;\n\n/**\n * Synchronous log collector with that only collects selected categories\n * @public\n */\nexport function withLogCollector<T extends LogFuncs>(\n logsToCollect: T[],\n callback: SyncLogCollector,\n): CollectedLogs<T>;\n\n/**\n * Log collector that collect logs either from a sync or async collector.\n * @public\n */\nexport function withLogCollector(\n logsToCollect: LogFuncs[] | LogCollector,\n callback?: LogCollector,\n): CollectedLogs<LogFuncs> | Promise<CollectedLogs<LogFuncs>> {\n const oneArg = !callback;\n const actualCallback = (oneArg ? logsToCollect : callback) as LogCollector;\n const categories = (oneArg ? allCategories : logsToCollect) as LogFuncs[];\n\n const logs = {\n log: new Array<string>(),\n warn: new Array<string>(),\n error: new Array<string>(),\n };\n\n const origLog = console.log;\n const origWarn = console.warn;\n const origError = console.error;\n\n if (categories.includes('log')) {\n console.log = (message: string) => {\n logs.log.push(message);\n };\n }\n if (categories.includes('warn')) {\n console.warn = (message: string) => {\n logs.warn.push(message);\n };\n }\n if (categories.includes('error')) {\n console.error = (message: string) => {\n logs.error.push(message);\n };\n }\n\n const restore = () => {\n console.log = origLog;\n console.warn = origWarn;\n console.error = origError;\n };\n\n try {\n const ret = actualCallback();\n\n if (!ret || !ret.then) {\n restore();\n return logs;\n }\n\n return ret.then(\n () => {\n restore();\n return logs;\n },\n error => {\n restore();\n throw error;\n },\n );\n } catch (error) {\n restore();\n throw error;\n }\n}\n"],"names":[],"mappings":"AA4CA,MAAM,aAAgB,GAAA,CAAC,KAAO,EAAA,MAAA,EAAQ,OAAO,CAAA
|
|
1
|
+
{"version":3,"file":"logCollector.esm.js","sources":["../../src/testUtils/logCollector.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* eslint-disable no-console */\n\n/**\n * Severity levels of {@link CollectedLogs}\n * @public\n */\nexport type LogFuncs = 'log' | 'warn' | 'error';\n/**\n * AsyncLogCollector type used in {@link (withLogCollector:1)} callback function.\n * @public\n */\nexport type AsyncLogCollector = () => Promise<void>;\n/**\n * SyncLogCollector type used in {@link (withLogCollector:2)} callback function.\n * @public\n */\nexport type SyncLogCollector = () => void;\n/**\n * Union type used in {@link (withLogCollector:3)} callback function.\n * @public\n */\nexport type LogCollector = AsyncLogCollector | SyncLogCollector;\n/**\n * Map of severity level and corresponding log lines.\n * @public\n */\nexport type CollectedLogs<T extends LogFuncs> = { [key in T]: string[] };\n\nconst allCategories = ['log', 'warn', 'error'];\n\n/**\n * Asynchronous log collector with that collects all categories\n * @public\n */\nexport function withLogCollector(\n callback: AsyncLogCollector,\n): Promise<CollectedLogs<LogFuncs>>;\n\n/**\n * Synchronous log collector with that collects all categories\n * @public\n */\nexport function withLogCollector(\n callback: SyncLogCollector,\n): CollectedLogs<LogFuncs>;\n\n/**\n * Asynchronous log collector with that only collects selected categories\n * @public\n */\nexport function withLogCollector<T extends LogFuncs>(\n logsToCollect: T[],\n callback: AsyncLogCollector,\n): Promise<CollectedLogs<T>>;\n\n/**\n * Synchronous log collector with that only collects selected categories\n * @public\n */\nexport function withLogCollector<T extends LogFuncs>(\n logsToCollect: T[],\n callback: SyncLogCollector,\n): CollectedLogs<T>;\n\n/**\n * Log collector that collect logs either from a sync or async collector.\n * @public\n */\nexport function withLogCollector(\n logsToCollect: LogFuncs[] | LogCollector,\n callback?: LogCollector,\n): CollectedLogs<LogFuncs> | Promise<CollectedLogs<LogFuncs>> {\n const oneArg = !callback;\n const actualCallback = (oneArg ? logsToCollect : callback) as LogCollector;\n const categories = (oneArg ? allCategories : logsToCollect) as LogFuncs[];\n\n const logs = {\n log: new Array<string>(),\n warn: new Array<string>(),\n error: new Array<string>(),\n };\n\n const origLog = console.log;\n const origWarn = console.warn;\n const origError = console.error;\n\n if (categories.includes('log')) {\n console.log = (message: string) => {\n logs.log.push(message);\n };\n }\n if (categories.includes('warn')) {\n console.warn = (message: string) => {\n logs.warn.push(message);\n };\n }\n if (categories.includes('error')) {\n console.error = (message: string) => {\n logs.error.push(message);\n };\n }\n\n const restore = () => {\n console.log = origLog;\n console.warn = origWarn;\n console.error = origError;\n };\n\n try {\n const ret = actualCallback();\n\n if (!ret || !ret.then) {\n restore();\n return logs;\n }\n\n return ret.then(\n () => {\n restore();\n return logs;\n },\n error => {\n restore();\n throw error;\n },\n );\n } catch (error) {\n restore();\n throw error;\n }\n}\n"],"names":[],"mappings":"AA4CA,MAAM,aAAgB,GAAA,CAAC,KAAO,EAAA,MAAA,EAAQ,OAAO,CAAA;AAwC7B,SAAA,gBAAA,CACd,eACA,QAC4D,EAAA;AAC5D,EAAA,MAAM,SAAS,CAAC,QAAA;AAChB,EAAM,MAAA,cAAA,GAAkB,SAAS,aAAgB,GAAA,QAAA;AACjD,EAAM,MAAA,UAAA,GAAc,SAAS,aAAgB,GAAA,aAAA;AAE7C,EAAA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A;AAAA,MACT,MAAM;AACJ,QAAQ,OAAA,EAAA;AACR,QAAO,OAAA,IAAA;AAAA,OACT;AAAA,MACA,CAAS,KAAA,KAAA;AACP,QAAQ,OAAA,EAAA;AACR,QAAM,MAAA,KAAA;AAAA;AACR,KACF;AAAA,WACO,KAAO,EAAA;AACd,IAAQ,OAAA,EAAA;AACR,IAAM,MAAA,KAAA;AAAA;AAEV;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mockApis.esm.js","sources":["../../src/testUtils/mockApis.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createApiFactory,\n errorApiRef,\n fetchApiRef,\n storageApiRef,\n} from '@backstage/core-plugin-api';\nimport { translationApiRef } from '@backstage/core-plugin-api/alpha';\nimport { MockErrorApi, MockFetchApi, MockStorageApi } from './apis';\nimport { MockTranslationApi } from './apis/TranslationApi';\n\nexport const mockApis = [\n createApiFactory(errorApiRef, new MockErrorApi()),\n createApiFactory(fetchApiRef, new MockFetchApi()),\n createApiFactory(storageApiRef, MockStorageApi.create()),\n createApiFactory(translationApiRef, MockTranslationApi.create()),\n];\n"],"names":[],"mappings":";;;;;;;;;;AA0BO,MAAM,QAAW,GAAA;AAAA,EACtB,gBAAiB,CAAA,WAAA,EAAa,IAAI,YAAA,EAAc,CAAA;AAAA,EAChD,gBAAiB,CAAA,WAAA,EAAa,IAAI,YAAA,EAAc,CAAA;AAAA,EAChD,gBAAiB,CAAA,aAAA,EAAe,cAAe,CAAA,MAAA,EAAQ,CAAA;AAAA,EACvD,gBAAiB,CAAA,iBAAA,EAAmB,kBAAmB,CAAA,MAAA,EAAQ
|
|
1
|
+
{"version":3,"file":"mockApis.esm.js","sources":["../../src/testUtils/mockApis.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n createApiFactory,\n errorApiRef,\n fetchApiRef,\n storageApiRef,\n} from '@backstage/core-plugin-api';\nimport { translationApiRef } from '@backstage/core-plugin-api/alpha';\nimport { MockErrorApi, MockFetchApi, MockStorageApi } from './apis';\nimport { MockTranslationApi } from './apis/TranslationApi';\n\nexport const mockApis = [\n createApiFactory(errorApiRef, new MockErrorApi()),\n createApiFactory(fetchApiRef, new MockFetchApi()),\n createApiFactory(storageApiRef, MockStorageApi.create()),\n createApiFactory(translationApiRef, MockTranslationApi.create()),\n];\n"],"names":[],"mappings":";;;;;;;;;;AA0BO,MAAM,QAAW,GAAA;AAAA,EACtB,gBAAiB,CAAA,WAAA,EAAa,IAAI,YAAA,EAAc,CAAA;AAAA,EAChD,gBAAiB,CAAA,WAAA,EAAa,IAAI,YAAA,EAAc,CAAA;AAAA,EAChD,gBAAiB,CAAA,aAAA,EAAe,cAAe,CAAA,MAAA,EAAQ,CAAA;AAAA,EACvD,gBAAiB,CAAA,iBAAA,EAAmB,kBAAmB,CAAA,MAAA,EAAQ;AACjE;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mockBreakpoint.esm.js","sources":["../../src/testUtils/mockBreakpoint.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * This is a mocking method suggested in the Jest docs, as it is not implemented in JSDOM yet.\n * It can be used to mock values for the Material UI `useMediaQuery` hook if it is used in a tested component.\n *\n * For issues checkout the documentation:\n * https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom\n *\n * If there are any updates from Material UI React on testing `useMediaQuery` this mock should be replaced\n * https://mui.com/material-ui/react-use-media-query/#testing\n *\n * @public\n * @deprecated Import from `@backstage/core-components/testUtils` instead.\n */\nexport default function mockBreakpoint(options: { matches: boolean }) {\n Object.defineProperty(window, 'matchMedia', {\n writable: true,\n value: jest.fn().mockImplementation(query => ({\n matches: options.matches ?? false,\n media: query,\n onchange: null,\n addListener: jest.fn(), // deprecated\n removeListener: jest.fn(), // deprecated\n addEventListener: jest.fn(),\n removeEventListener: jest.fn(),\n dispatchEvent: jest.fn(),\n })),\n });\n}\n"],"names":[],"mappings":"AA6BA,SAAwB,eAAe,OAA+B,EAAA;AACpE,EAAO,MAAA,CAAA,cAAA,CAAe,QAAQ,YAAc,EAAA;AAAA,IAC1C,QAAU,EAAA,IAAA;AAAA,IACV,KAAO,EAAA,IAAA,CAAK,EAAG,EAAA,CAAE,mBAAmB,CAAU,KAAA,MAAA;AAAA,MAC5C,OAAA,EAAS,QAAQ,OAAW,IAAA,KAAA;AAAA,MAC5B,KAAO,EAAA,KAAA;AAAA,MACP,QAAU,EAAA,IAAA;AAAA,MACV,WAAA,EAAa,KAAK,EAAG,EAAA;AAAA;AAAA,MACrB,cAAA,EAAgB,KAAK,EAAG,EAAA;AAAA;AAAA,MACxB,gBAAA,EAAkB,KAAK,EAAG,EAAA;AAAA,MAC1B,mBAAA,EAAqB,KAAK,EAAG,EAAA;AAAA,MAC7B,aAAA,EAAe,KAAK,EAAG
|
|
1
|
+
{"version":3,"file":"mockBreakpoint.esm.js","sources":["../../src/testUtils/mockBreakpoint.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * This is a mocking method suggested in the Jest docs, as it is not implemented in JSDOM yet.\n * It can be used to mock values for the Material UI `useMediaQuery` hook if it is used in a tested component.\n *\n * For issues checkout the documentation:\n * https://jestjs.io/docs/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom\n *\n * If there are any updates from Material UI React on testing `useMediaQuery` this mock should be replaced\n * https://mui.com/material-ui/react-use-media-query/#testing\n *\n * @public\n * @deprecated Import from `@backstage/core-components/testUtils` instead.\n */\nexport default function mockBreakpoint(options: { matches: boolean }) {\n Object.defineProperty(window, 'matchMedia', {\n writable: true,\n value: jest.fn().mockImplementation(query => ({\n matches: options.matches ?? false,\n media: query,\n onchange: null,\n addListener: jest.fn(), // deprecated\n removeListener: jest.fn(), // deprecated\n addEventListener: jest.fn(),\n removeEventListener: jest.fn(),\n dispatchEvent: jest.fn(),\n })),\n });\n}\n"],"names":[],"mappings":"AA6BA,SAAwB,eAAe,OAA+B,EAAA;AACpE,EAAO,MAAA,CAAA,cAAA,CAAe,QAAQ,YAAc,EAAA;AAAA,IAC1C,QAAU,EAAA,IAAA;AAAA,IACV,KAAO,EAAA,IAAA,CAAK,EAAG,EAAA,CAAE,mBAAmB,CAAU,KAAA,MAAA;AAAA,MAC5C,OAAA,EAAS,QAAQ,OAAW,IAAA,KAAA;AAAA,MAC5B,KAAO,EAAA,KAAA;AAAA,MACP,QAAU,EAAA,IAAA;AAAA,MACV,WAAA,EAAa,KAAK,EAAG,EAAA;AAAA;AAAA,MACrB,cAAA,EAAgB,KAAK,EAAG,EAAA;AAAA;AAAA,MACxB,gBAAA,EAAkB,KAAK,EAAG,EAAA;AAAA,MAC1B,mBAAA,EAAqB,KAAK,EAAG,EAAA;AAAA,MAC7B,aAAA,EAAe,KAAK,EAAG;AAAA,KACvB,CAAA;AAAA,GACH,CAAA;AACH;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registerMswTestHooks.esm.js","sources":["../../../src/testUtils/msw/registerMswTestHooks.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Sets up handlers for request mocking\n * @public\n * @param worker - service worker\n */\nexport function registerMswTestHooks(worker: {\n listen: (t: any) => void;\n close: () => void;\n resetHandlers: () => void;\n}) {\n beforeAll(() => worker.listen({ onUnhandledRequest: 'error' }));\n afterAll(() => worker.close());\n afterEach(() => worker.resetHandlers());\n}\n"],"names":[],"mappings":"AAqBO,SAAS,qBAAqB,MAIlC,EAAA;AACD,EAAA,SAAA,CAAU,MAAM,MAAO,CAAA,MAAA,CAAO,EAAE,kBAAoB,EAAA,OAAA,EAAS,CAAC,CAAA
|
|
1
|
+
{"version":3,"file":"registerMswTestHooks.esm.js","sources":["../../../src/testUtils/msw/registerMswTestHooks.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Sets up handlers for request mocking\n * @public\n * @param worker - service worker\n */\nexport function registerMswTestHooks(worker: {\n listen: (t: any) => void;\n close: () => void;\n resetHandlers: () => void;\n}) {\n beforeAll(() => worker.listen({ onUnhandledRequest: 'error' }));\n afterAll(() => worker.close());\n afterEach(() => worker.resetHandlers());\n}\n"],"names":[],"mappings":"AAqBO,SAAS,qBAAqB,MAIlC,EAAA;AACD,EAAA,SAAA,CAAU,MAAM,MAAO,CAAA,MAAA,CAAO,EAAE,kBAAoB,EAAA,OAAA,EAAS,CAAC,CAAA;AAC9D,EAAS,QAAA,CAAA,MAAM,MAAO,CAAA,KAAA,EAAO,CAAA;AAC7B,EAAU,SAAA,CAAA,MAAM,MAAO,CAAA,aAAA,EAAe,CAAA;AACxC;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testingLibrary.esm.js","sources":["../../src/testUtils/testingLibrary.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ReactElement } from 'react';\nimport {\n act,\n render,\n RenderOptions,\n RenderResult,\n} from '@testing-library/react';\n\n/**\n * @public\n * Set legacy mode when using React 18/RTL 13+.\n * Mock this option while we're working against React 17 or lower.\n */\nexport type LegacyRootOption = { legacyRoot?: boolean };\n\n/**\n * @public\n * Simplifies rendering of async components in by taking care of the wrapping inside act\n *\n * @remarks\n *\n * Components using useEffect to perform an asynchronous action (such as fetch) must be rendered within an async\n * act call to properly get the final state, even with mocked responses. This utility method makes the signature a bit\n * cleaner, since act doesn't return the result of the evaluated function.\n * https://github.com/testing-library/react-testing-library/issues/281\n * https://github.com/facebook/react/pull/14853\n */\nexport async function renderWithEffects(\n nodes: ReactElement,\n options?: Pick<RenderOptions, 'wrapper'> & LegacyRootOption,\n): Promise<RenderResult> {\n let value: RenderResult;\n await act(async () => {\n value = render(nodes, options);\n });\n return value!;\n}\n"],"names":[],"mappings":";;AA2CsB,eAAA,iBAAA,CACpB,OACA,OACuB,EAAA;AACvB,EAAI,IAAA,KAAA
|
|
1
|
+
{"version":3,"file":"testingLibrary.esm.js","sources":["../../src/testUtils/testingLibrary.ts"],"sourcesContent":["/*\n * Copyright 2020 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ReactElement } from 'react';\nimport {\n act,\n render,\n RenderOptions,\n RenderResult,\n} from '@testing-library/react';\n\n/**\n * @public\n * Set legacy mode when using React 18/RTL 13+.\n * Mock this option while we're working against React 17 or lower.\n */\nexport type LegacyRootOption = { legacyRoot?: boolean };\n\n/**\n * @public\n * Simplifies rendering of async components in by taking care of the wrapping inside act\n *\n * @remarks\n *\n * Components using useEffect to perform an asynchronous action (such as fetch) must be rendered within an async\n * act call to properly get the final state, even with mocked responses. This utility method makes the signature a bit\n * cleaner, since act doesn't return the result of the evaluated function.\n * https://github.com/testing-library/react-testing-library/issues/281\n * https://github.com/facebook/react/pull/14853\n */\nexport async function renderWithEffects(\n nodes: ReactElement,\n options?: Pick<RenderOptions, 'wrapper'> & LegacyRootOption,\n): Promise<RenderResult> {\n let value: RenderResult;\n await act(async () => {\n value = render(nodes, options);\n });\n return value!;\n}\n"],"names":[],"mappings":";;AA2CsB,eAAA,iBAAA,CACpB,OACA,OACuB,EAAA;AACvB,EAAI,IAAA,KAAA;AACJ,EAAA,MAAM,IAAI,YAAY;AACpB,IAAQ,KAAA,GAAA,MAAA,CAAO,OAAO,OAAO,CAAA;AAAA,GAC9B,CAAA;AACD,EAAO,OAAA,KAAA;AACT;;;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@backstage/test-utils",
|
|
3
|
-
"version": "1.7.1
|
|
3
|
+
"version": "1.7.1",
|
|
4
4
|
"description": "Utilities to test Backstage plugins and apps.",
|
|
5
5
|
"backstage": {
|
|
6
6
|
"role": "web-library"
|
|
@@ -34,9 +34,18 @@
|
|
|
34
34
|
},
|
|
35
35
|
"main": "./dist/index.esm.js",
|
|
36
36
|
"types": "./dist/index.d.ts",
|
|
37
|
+
"typesVersions": {
|
|
38
|
+
"*": {
|
|
39
|
+
"index": [
|
|
40
|
+
"dist/index.d.ts"
|
|
41
|
+
],
|
|
42
|
+
"alpha": [
|
|
43
|
+
"dist/alpha.d.ts"
|
|
44
|
+
]
|
|
45
|
+
}
|
|
46
|
+
},
|
|
37
47
|
"files": [
|
|
38
|
-
"dist"
|
|
39
|
-
"alpha"
|
|
48
|
+
"dist"
|
|
40
49
|
],
|
|
41
50
|
"scripts": {
|
|
42
51
|
"build": "backstage-cli package build",
|
|
@@ -48,13 +57,13 @@
|
|
|
48
57
|
"test": "backstage-cli package test"
|
|
49
58
|
},
|
|
50
59
|
"dependencies": {
|
|
51
|
-
"@backstage/config": "1.
|
|
52
|
-
"@backstage/core-app-api": "1.15.
|
|
53
|
-
"@backstage/core-plugin-api": "1.10.
|
|
54
|
-
"@backstage/plugin-permission-common": "0.8.
|
|
55
|
-
"@backstage/plugin-permission-react": "0.4.
|
|
56
|
-
"@backstage/theme": "0.6.1
|
|
57
|
-
"@backstage/types": "1.
|
|
60
|
+
"@backstage/config": "^1.3.0",
|
|
61
|
+
"@backstage/core-app-api": "^1.15.2",
|
|
62
|
+
"@backstage/core-plugin-api": "^1.10.1",
|
|
63
|
+
"@backstage/plugin-permission-common": "^0.8.2",
|
|
64
|
+
"@backstage/plugin-permission-react": "^0.4.28",
|
|
65
|
+
"@backstage/theme": "^0.6.1",
|
|
66
|
+
"@backstage/types": "^1.2.0",
|
|
58
67
|
"@material-ui/core": "^4.12.2",
|
|
59
68
|
"@material-ui/icons": "^4.9.1",
|
|
60
69
|
"cross-fetch": "^4.0.0",
|
|
@@ -62,7 +71,7 @@
|
|
|
62
71
|
"zen-observable": "^0.10.0"
|
|
63
72
|
},
|
|
64
73
|
"devDependencies": {
|
|
65
|
-
"@backstage/cli": "0.29.0
|
|
74
|
+
"@backstage/cli": "^0.29.0",
|
|
66
75
|
"@testing-library/jest-dom": "^6.0.0",
|
|
67
76
|
"@types/jest": "*",
|
|
68
77
|
"@types/react": "^18.0.0",
|