or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

app-wrappers.mdindex.mdmock-apis.mdmsw-integration.mdtest-api-provider.mdtesting-utilities.md
tile.json

tessl/npm-backstage--test-utils

Testing utilities for Backstage plugins and applications with mock APIs, app wrappers, and test helpers.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@backstage/test-utils@1.7.x

To install, run

npx @tessl/cli install tessl/npm-backstage--test-utils@1.7.0

index.mddocs/

Backstage Test Utils

Backstage Test Utils provides comprehensive testing utilities specifically designed for Backstage plugins and applications. It offers mock API implementations, app wrappers for consistent test setup, testing library enhancements, and MSW integration for HTTP mocking.

Package Information

  • Package Name: @backstage/test-utils
  • Package Type: npm
  • Language: TypeScript
  • Installation: yarn add --dev @backstage/test-utils or npm install --save-dev @backstage/test-utils

Core Imports

import {
  TestApiProvider,
  mockApis,
  wrapInTestApp,
  renderInTestApp,
  withLogCollector,
  registerMswTestHooks
} from "@backstage/test-utils";

CommonJS:

const {
  TestApiProvider,
  mockApis,
  wrapInTestApp,
  renderInTestApp
} = require("@backstage/test-utils");

Alpha exports (Translation API mocks):

import { MockTranslationApi } from "@backstage/test-utils/alpha";

Basic Usage

import { 
  TestApiProvider, 
  mockApis, 
  renderInTestApp 
} from "@backstage/test-utils";
import { render } from "@testing-library/react";

// Test component with mock APIs
function TestWrapper() {
  return (
    <TestApiProvider 
      apis={[
        [configApiRef, mockApis.config({ data: { app: { title: 'Test App' } } })],
        [identityApiRef, mockApis.identity()]
      ]}
    >
      <MyBackstageComponent />
    </TestApiProvider>
  );
}

// Render component in full Backstage app context
const { getByText } = await renderInTestApp(<MyPluginPage />);
expect(getByText('Plugin Content')).toBeInTheDocument();

Architecture

Backstage Test Utils is organized around several key areas:

  • Mock API System: Both legacy individual mocks and modern mockApis namespace with three usage patterns (fake, factory, mock)
  • App Wrappers: Complete test app context including routing, theming, and API providers
  • Test API Provider: Type-safe API registration system for injecting mock dependencies
  • Testing Utilities: Log collection, async rendering helpers, breakpoint mocking
  • MSW Integration: Mock Service Worker setup utilities for HTTP mocking
  • Default Configurations: Pre-configured API sets for common testing scenarios

Capabilities

Mock APIs

Modern mock implementations of core Backstage APIs with consistent patterns across all API types. Each mock provides fake implementations, factory creators, and Jest mock instances.

interface MockApisNamespace {
  analytics(): AnalyticsApi;
  analytics.factory(): ApiFactory<AnalyticsApi, AnalyticsApi, {}>;
  analytics.mock(partialImpl?: Partial<AnalyticsApi>): ApiMock<AnalyticsApi>;
  
  config(options?: { data?: JsonObject }): ConfigApi;
  config.factory(): ApiFactory<ConfigApi, ConfigApi, {}>;
  config.mock(): ApiMock<ConfigApi>;
  
  discovery(options?: { baseUrl?: string }): DiscoveryApi;
  identity(options?: IdentityOptions): IdentityApi;
  permission(options?: PermissionOptions): PermissionApi;
  storage(options?: { data?: JsonObject }): StorageApi;
  translation(): TranslationApi;
}

type ApiMock<TApi> = {
  factory: ApiFactory<TApi, TApi, {}>;
} & { [K in keyof TApi]: jest.MockedFunction<TApi[K]> };

Mock APIs

App Testing Wrappers

Complete Backstage app context for testing components with routing, theming, and API providers configured automatically.

function wrapInTestApp(
  Component: ComponentType | ReactNode, 
  options?: TestAppOptions
): ReactElement;

function renderInTestApp(
  Component: ComponentType | ReactNode,
  options?: TestAppOptions & LegacyRootOption
): Promise<RenderResult>;

function createTestAppWrapper(options?: TestAppOptions): ComponentWrapper;

interface TestAppOptions {
  routeEntries?: string[];
  mountedRoutes?: { [path: string]: RouteRef | ExternalRouteRef };
  components?: Partial<AppComponents>;
  icons?: Partial<AppIcons> & { [key: string]: IconComponent };
}

App Wrappers

Test API Provider

Type-safe API context provider for tests with flexible API registration and registry management.

function TestApiProvider<T extends readonly ApiPair[]>(
  props: TestApiProviderProps<T>
): JSX.Element;

interface TestApiProviderProps<TApiPairs extends readonly ApiPair[]> {
  apis: TApiPairs;
  children: ReactNode;
}

class TestApiRegistry {
  static from<TApiPairs extends readonly ApiPair[]>(...apis: TApiPairs): TestApiRegistry;
  get<T>(api: ApiRef<T>): T | undefined;
}

type ApiPair = readonly [ApiRef<any>, any];

Test API Provider

Testing Utilities

Enhanced testing capabilities including log collection, async rendering, and breakpoint mocking for comprehensive test coverage.

function withLogCollector(callback: () => Promise<void>): Promise<CollectedLogs<LogFuncs>>;
function withLogCollector(callback: () => void): CollectedLogs<LogFuncs>;

function renderWithEffects(
  nodes: ReactElement,
  options?: RenderOptions & LegacyRootOption
): Promise<RenderResult>;

function textContentMatcher(text: string): MatcherFunction;

Testing Utilities

MSW Integration

Mock Service Worker integration for HTTP request mocking in tests.

function registerMswTestHooks(worker: {
  listen: (t: any) => void;
  close: () => void;
  resetHandlers: () => void;
}): void;

MSW Integration

Types

type ComponentWrapper = (props: { children?: ReactNode }) => JSX.Element;

type LogFuncs = 'log' | 'warn' | 'error';
type CollectedLogs<T extends readonly string[]> = { [K in T[number]]: string[] };

interface LegacyRootOption {
  legacyRoot?: boolean;
}

interface IdentityOptions {
  userEntityRef?: string;
  ownershipEntityRefs?: string[];
  token?: string;
  email?: string;
  displayName?: string;
  picture?: string;
}

interface PermissionOptions {
  authorize?: 
    | AuthorizeResult.ALLOW
    | AuthorizeResult.DENY 
    | ((request: EvaluatePermissionRequest) => AuthorizeResult.ALLOW | AuthorizeResult.DENY);
}