Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions packages/app/src/api/LearningPathApiClient.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import {
ConfigApi,
DiscoveryApi,
IdentityApi,
} from '@backstage/core-plugin-api';

import { LearningPathApiClient } from './LearningPathApiClient';

const learningPaths = [
{
label: 'Operators on OpenShift',
url: 'https://example.com',
minutes: 20,
paths: 6,
},
];

const buildClient = (opts?: { proxyPath?: string; token?: string }) => {
const discoveryApi = {
getBaseUrl: jest.fn().mockResolvedValue('http://localhost/api/proxy'),
} as unknown as DiscoveryApi;
const configApi = {
getOptionalString: jest.fn().mockReturnValue(opts?.proxyPath),
} as unknown as ConfigApi;
const identityApi = {
getCredentials: jest.fn().mockResolvedValue({ token: opts?.token }),
} as unknown as IdentityApi;
return new LearningPathApiClient({ discoveryApi, configApi, identityApi });
};

describe('LearningPathApiClient', () => {
let fetchSpy: jest.SpyInstance;

beforeEach(() => {
fetchSpy = jest
.spyOn(global, 'fetch')
.mockResolvedValue(
new Response(JSON.stringify(learningPaths), { status: 200 }),
);
});

afterEach(() => jest.restoreAllMocks());

it('fetches learning paths from the default proxy path with a bearer token', async () => {
const data = await buildClient({ token: 'tok-1' }).getLearningPathData();

expect(data).toEqual(learningPaths);
expect(fetchSpy).toHaveBeenCalledWith(
'http://localhost/api/proxy/developer-hub/learning-paths',
expect.objectContaining({
headers: expect.objectContaining({ Authorization: 'Bearer tok-1' }),
}),
);
});

it('uses the configured developerHub.proxyPath when set', async () => {
await buildClient({
proxyPath: '/custom',
token: 'tok',
}).getLearningPathData();

expect(fetchSpy).toHaveBeenCalledWith(
'http://localhost/api/proxy/custom/learning-paths',
expect.anything(),
);
});

it('omits the Authorization header when there is no token', async () => {
await buildClient({}).getLearningPathData();

const [, init] = fetchSpy.mock.calls[0];
expect(init.headers).not.toHaveProperty('Authorization');
});

it('throws a descriptive error when the response is not ok', async () => {
fetchSpy.mockResolvedValue(
new Response('nope', { status: 500, statusText: 'Server Error' }),
);

await expect(
buildClient({ token: 'tok' }).getLearningPathData(),
).rejects.toThrow(/status 500: Server Error/);
});
});
84 changes: 84 additions & 0 deletions packages/app/src/components/ErrorPages/ErrorPage.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { configApiRef } from '@backstage/core-plugin-api';
import {
mockApis,
renderInTestApp,
TestApiProvider,
} from '@backstage/test-utils';

import { screen } from '@testing-library/react';

import { ErrorPage, ErrorPageProps } from './ErrorPage';

jest.mock('../../hooks/useTranslation', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));

const renderErrorPage = async (props: ErrorPageProps) =>
renderInTestApp(
<TestApiProvider apis={[[configApiRef, mockApis.config({ data: {} })]]}>
<ErrorPage {...props} />
</TestApiProvider>,
);

describe('ErrorPage', () => {
const originalHistoryLength = window.history.length;

afterEach(() => {
Object.defineProperty(window.history, 'length', {
value: originalHistoryLength,
configurable: true,
});
});

it('renders the status, message and additional info', async () => {
await renderErrorPage({
status: '500',
statusMessage: 'Internal Server Error',
additionalInfo: 'Something went wrong',
});

expect(screen.getByText('500')).toBeInTheDocument();
expect(screen.getByText('Internal Server Error')).toBeInTheDocument();
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
});

it('always offers the contact-support action', async () => {
await renderErrorPage({ status: '500', statusMessage: 'Error' });

expect(
screen.getByRole('link', { name: 'app.errors.contactSupport' }),
).toBeInTheDocument();
});

it('renders the stack trace when one is provided', async () => {
await renderErrorPage({
status: '500',
statusMessage: 'Error',
stack: 'Error: boom\n at foo',
});

expect(screen.getByText(/Error: boom/)).toBeInTheDocument();
});

it('omits the go-back action for non-404 errors', async () => {
await renderErrorPage({ status: '500', statusMessage: 'Error' });

expect(
screen.queryByRole('button', { name: 'app.errors.goBack' }),
).not.toBeInTheDocument();
});

it('offers the go-back action for 404 errors when there is history', async () => {
// GoBackButton only renders when there is meaningful history to go back to.
Object.defineProperty(window.history, 'length', {
value: 3,
configurable: true,
});

await renderErrorPage({ status: '404', statusMessage: 'Not Found' });

expect(
screen.getByRole('button', { name: 'app.errors.goBack' }),
).toBeInTheDocument();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { configApiRef } from '@backstage/core-plugin-api';
import {
mockApis,
renderInTestApp,
TestApiProvider,
} from '@backstage/test-utils';

import { screen } from '@testing-library/react';

import { ContactSupportButton } from './ContactSupportButton';

jest.mock('../../../hooks/useTranslation', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));

const renderButton = async (
props: { supportUrl?: string } = {},
configData: object = {},
) =>
renderInTestApp(
<TestApiProvider
apis={[[configApiRef, mockApis.config({ data: configData })]]}
>
<ContactSupportButton {...props} />
</TestApiProvider>,
);

const supportLink = () =>
screen.getByRole('link', { name: 'app.errors.contactSupport' });

describe('ContactSupportButton', () => {
it('prefers the explicit supportUrl prop', async () => {
await renderButton(
{ supportUrl: 'https://prop.example.com' },
{ app: { support: { url: 'https://config.example.com' } } },
);

expect(supportLink()).toHaveAttribute('href', 'https://prop.example.com');
});

it('falls back to the configured support URL', async () => {
await renderButton(
{},
{ app: { support: { url: 'https://config.example.com' } } },
);

expect(supportLink()).toHaveAttribute('href', 'https://config.example.com');
});

it('falls back to the default Red Hat support URL', async () => {
await renderButton({}, {});

expect(supportLink()).toHaveAttribute(
'href',
'https://access.redhat.com/documentation/red_hat_developer_hub',
);
});
});
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we really need to tests for button that just calls navigate(-1);?

This feels like writing tests only for sake of writing tests and increasing coverage numbers rather than providing actual value.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was already written so we can keep it. But I don't think that it makes much sense to test functions like this.
ContactSupportButton and ErrorPage are similar stories.

Copy link
Copy Markdown
Member Author

@gustavolira gustavolira May 26, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we really need to tests for button that just calls navigate(-1);?

This feels like writing tests only for sake of writing tests and increasing coverage numbers rather than providing actual value.

The real value there is the conditional rendering, not the click itself

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was already written so we can keep it. But I don't think that it makes much sense to test functions like this. ContactSupportButton and ErrorPage are similar stories.

Agree they're simple components, but ContactSupportButton has a 3-level fallback (prop, config, default URL) that can break silently, and ErrorPage has conditional logic worth covering. Not strictly required, but I think they add some value.

Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { render, screen } from '@testing-library/react';
import { userEvent } from '@testing-library/user-event';

import { GoBackButton } from './GoBackButton';

const mockNavigate = jest.fn();

// useNavigate is mocked, so no router context (MemoryRouter) is needed.
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: () => mockNavigate,
}));

jest.mock('../../../hooks/useTranslation', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));

const setHistoryLength = (length: number) =>
Object.defineProperty(window.history, 'length', {
value: length,
configurable: true,
});

const renderButton = () => render(<GoBackButton />);

describe('GoBackButton', () => {
const originalHistoryLength = window.history.length;

afterEach(() => {
jest.clearAllMocks();
setHistoryLength(originalHistoryLength);
});

it('navigates back when there is history to go back to', async () => {
setHistoryLength(3);

renderButton();
await userEvent.click(
screen.getByRole('button', { name: 'app.errors.goBack' }),
);

expect(mockNavigate).toHaveBeenCalledWith(-1);
});

it('renders nothing when there is no meaningful history', () => {
setHistoryLength(1);

renderButton();

expect(
screen.queryByRole('button', { name: 'app.errors.goBack' }),
).not.toBeInTheDocument();
});
});
66 changes: 66 additions & 0 deletions packages/app/src/components/Root/MenuIcon.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { useApp } from '@backstage/core-plugin-api';

import { render, screen } from '@testing-library/react';

import { MenuIcon } from './MenuIcon';

jest.mock('@backstage/core-plugin-api', () => ({
...jest.requireActual('@backstage/core-plugin-api'),
useApp: jest.fn(),
}));

const mockGetSystemIcon = jest.fn();

beforeEach(() => {
mockGetSystemIcon.mockReset();
(useApp as jest.Mock).mockReturnValue({ getSystemIcon: mockGetSystemIcon });
});

describe('MenuIcon', () => {
it('renders nothing when the icon is empty', () => {
const { container } = render(<MenuIcon icon="" />);

expect(container).toBeEmptyDOMElement();
});

it('renders the registered system icon when one matches', () => {
const SystemIcon = () => <svg data-testid="system-icon" />;
mockGetSystemIcon.mockReturnValue(SystemIcon);

render(<MenuIcon icon="user" />);

expect(screen.getByTestId('system-icon')).toBeInTheDocument();
});

it('renders an inline SVG icon as a base64 image', () => {
mockGetSystemIcon.mockReturnValue(undefined);

const { container } = render(<MenuIcon icon="<svg></svg>" />);

expect(container.querySelector('img')).toHaveAttribute(
'src',
expect.stringContaining('data:image/svg+xml;base64,'),
);
});

it('renders a URL icon using the URL as the image source', () => {
mockGetSystemIcon.mockReturnValue(undefined);

const { container } = render(
<MenuIcon icon="https://example.com/icon.png" />,
);

expect(container.querySelector('img')).toHaveAttribute(
'src',
'https://example.com/icon.png',
);
});

it('renders a material icon name as text', () => {
mockGetSystemIcon.mockReturnValue(undefined);

render(<MenuIcon icon="home" />);

expect(screen.getByText('home')).toBeInTheDocument();
});
});
Loading
Loading