catalog-react: factory mock shortcut for catalogApiMock

Signed-off-by: Patrik Oldsberg <poldsberg@gmail.com>
This commit is contained in:
Patrik Oldsberg
2026-02-05 23:36:53 +01:00
parent 0d7e331265
commit 6362ca4b17
8 changed files with 68 additions and 30 deletions
@@ -19,7 +19,7 @@ export {
type MockApiFactorySymbol,
type ApiMock,
type MockWithApiFactory,
mockApiFactorySymbol,
attachMockApiFactory,
} from './utils';
/**
+32 -1
View File
@@ -20,7 +20,7 @@ import { ApiFactory } from '@backstage/frontend-plugin-api';
/**
* Symbol used to mark mock API instances with their corresponding API factory.
*
* @public
* @ignore
*/
export const mockApiFactorySymbol = Symbol.for('@backstage/mock-api');
@@ -78,6 +78,37 @@ export function mockWithApiFactory<TApi, TImpl extends TApi = TApi>(
return marked;
}
/**
* Attaches mock API factory metadata to an API instance, allowing it to be
* passed directly to test utilities without needing to explicitly provide
* the [apiRef, implementation] tuple.
*
* @public
* @example
* ```ts
* const catalogApi = attachMockApiFactory(
* catalogApiRef,
* new InMemoryCatalogClient()
* );
* // Can now be passed directly to TestApiProvider
* <TestApiProvider apis={[catalogApi]}>
* ```
*/
export function attachMockApiFactory<TApi, TImpl extends TApi = TApi>(
apiRef: ApiRef<TApi>,
implementation: TImpl,
): TImpl & { [mockApiFactorySymbol]: ApiFactory<TApi, TApi, {}> } {
const marked = implementation as TImpl & {
[mockApiFactorySymbol]: ApiFactory<TApi, TApi, {}>;
};
(marked as any)[mockApiFactorySymbol] = {
api: apiRef,
deps: {},
factory: () => implementation,
};
return marked;
}
/**
* Retrieves the API factory from a mock API instance.
* Returns undefined if the value is not a mock API instance.