import React from 'react';
import { screen, waitFor, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import '@testing-library/jest-dom';
import { useFullscreen } from '~/shared/hooks/fullscreen';
import { useTheme } from '~/shared/theme';
import { mockConsole, MockConsole } from '~/unit-test-utils';
import { renderWithQueryClientAndRouter as render } from '~/unit-test-utils/rendering-utils';
import LogViewer from '../LogViewer';
import { useAutoScrollWithResume } from '../useAutoScrollWithResume';
import { LOG_WRAP_LINES_STORAGE_KEY } from '../useLineWrap';
import { useLogViewerTheme } from '../useLogViewerTheme';
jest.mock('~/shared/hooks/useContainerHeight', () => ({
useContainerHeight: () => ({
containerRef: { current: document.createElement('div') },
containerHeight: 600,
}),
}));
// Mock only external dependencies and browser APIs
jest.mock('file-saver', () => ({
saveAs: jest.fn(),
}));
jest.mock('~/shared/hooks/fullscreen', () => ({
useFullscreen: jest.fn(() => [false, jest.fn(), jest.fn(), true]),
}));
jest.mock('~/shared/theme', () => ({
useTheme: jest.fn(() => ({
preference: 'system',
effectiveTheme: 'light',
systemPreference: 'light',
setThemePreference: jest.fn(),
})),
}));
jest.mock('../useLogViewerTheme', () => ({
useLogViewerTheme: jest.fn(() => ['dark', jest.fn()]),
}));
// Spy on the real implementation so we can assert on the args LogViewer passes it,
// while keeping its actual behavior intact for other tests in this file.
jest.mock('../useAutoScrollWithResume', () => {
const actual: typeof import('../useAutoScrollWithResume') = jest.requireActual(
'../useAutoScrollWithResume',
);
return {
...actual,
useAutoScrollWithResume: jest.fn(actual.useAutoScrollWithResume),
};
});
const mockSaveAs = jest.requireMock('file-saver').saveAs as jest.Mock;
const mockUseFullscreen = useFullscreen as jest.Mock;
const mockUseTheme = useTheme as jest.Mock;
const mockUseLogViewerTheme = useLogViewerTheme as jest.Mock;
const mockUseAutoScrollWithResume = useAutoScrollWithResume as jest.Mock;
describe('LogViewer Integration Tests', () => {
let consoleMock: MockConsole;
const mockTaskRun = {
apiVersion: 'tekton.dev/v1beta1',
kind: 'TaskRun',
metadata: {
name: 'test-task-run',
namespace: 'test-namespace',
},
spec: {
taskRef: {
name: 'test-task',
},
},
status: {
startTime: '2024-01-01T00:00:00Z',
completionTime: '2024-01-01T00:01:00Z',
},
};
const defaultProps = {
sections: [{ containerName: '', data: 'line 1\nline 2\nline 3\nline 4\nline 5' }],
isLoading: false,
errorMessage: null,
taskRun: mockTaskRun,
};
beforeEach(() => {
jest.clearAllMocks();
window.localStorage.removeItem(LOG_WRAP_LINES_STORAGE_KEY);
// Setup DOM dimensions for virtualization to work properly
Object.defineProperty(HTMLElement.prototype, 'offsetHeight', {
configurable: true,
value: 600,
});
Object.defineProperty(HTMLElement.prototype, 'offsetWidth', {
configurable: true,
value: 800,
});
Object.defineProperty(HTMLElement.prototype, 'clientHeight', {
configurable: true,
value: 600,
});
Object.defineProperty(HTMLElement.prototype, 'clientWidth', {
configurable: true,
value: 800,
});
mockUseFullscreen.mockReturnValue([false, jest.fn(), jest.fn(), true]);
mockUseTheme.mockReturnValue({
preference: 'system',
effectiveTheme: 'light',
systemPreference: 'light',
setThemePreference: jest.fn(),
});
mockUseLogViewerTheme.mockReturnValue(['dark', jest.fn()]);
// Suppress console output in test environment
consoleMock = mockConsole();
});
afterEach(() => {
consoleMock.restore();
jest.restoreAllMocks();
});
describe('Full component rendering', () => {
it('should render complete LogViewer with all sections', () => {
const { container } = render();
// Check container structure
const logViewerContainer = container.querySelector('.log-viewer__container');
expect(logViewerContainer).toBeInTheDocument();
// Check PatternFly log viewer class
const pfLogViewer = container.querySelector('.pf-v6-c-log-viewer');
expect(pfLogViewer).toBeInTheDocument();
// Check header section
const header = container.querySelector('.pf-v6-c-log-viewer__header');
expect(header).toBeInTheDocument();
// Check toolbar
const toolbar = container.querySelector('.pf-v6-c-toolbar');
expect(toolbar).toBeInTheDocument();
// Check main content area
const main = container.querySelector('.pf-v6-c-log-viewer__main');
expect(main).toBeInTheDocument();
const scrollContainer = container.querySelector('.log-content__list');
expect(scrollContainer).toBeInTheDocument();
});
it('should render task name in banner', () => {
const { container } = render();
const banner = container.querySelector('[data-test="logs-taskName"]');
expect(banner).toBeInTheDocument();
expect(banner).toHaveTextContent('test-task');
});
it('should render virtualized log content', () => {
const { container } = render();
const logList = container.querySelector('.log-content__list');
expect(logList).toBeInTheDocument();
const listItems = container.querySelectorAll('.pf-v6-c-log-viewer__list-item');
expect(listItems.length).toBeGreaterThan(0);
});
it('should render all toolbar buttons', () => {
render();
expect(screen.getByLabelText('Dark theme')).toBeInTheDocument();
expect(screen.getByLabelText('Wrap lines')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /download logs/i })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /expand/i })).toBeInTheDocument();
});
it('should render search input when showSearch is true', () => {
render();
const searchInput = screen.getByPlaceholderText('Search');
expect(searchInput).toBeInTheDocument();
});
it('should not render search input when showSearch is false', () => {
render();
const searchInput = screen.queryByPlaceholderText('Search');
expect(searchInput).not.toBeInTheDocument();
});
});
describe('ANSI escape code processing', () => {
it('should strip ANSI escape codes from log data', () => {
const dataWithAnsi = '\x1b[32mSuccess\x1b[0m\n\x1b[31mError\x1b[0m\nPlain text';
const { container } = render(
,
);
// Virtualization may not render all lines, but the visible ones should have ANSI codes stripped
// Check that rendered content doesn't contain ANSI escape codes
const logList = container.querySelector('.log-content__list');
expect(logList?.textContent).not.toContain('\x1b');
// Verify that at least one of the visible lines is rendered with stripped ANSI codes
expect(screen.getByText(/Plain text/)).toBeInTheDocument();
});
it('should handle carriage returns in log data', () => {
const dataWithCR = 'line 1\roverwrite\nline 2';
const { container } = render(
,
);
// \r should be replaced with \n - check that processed lines are visible
const logList = container.querySelector('.log-content__list');
expect(logList?.textContent).toContain('overwrite');
expect(logList?.textContent).toContain('line 2');
});
});
describe('Auto-scroll behavior', () => {
it('should render with auto-scroll enabled', () => {
const { container } = render();
const scrollContainer = container.querySelector('.log-content__list');
expect(scrollContainer).toBeInTheDocument();
// Should render all log lines with virtualization
const logItems = container.querySelectorAll('.pf-v6-c-log-viewer__list-item');
expect(logItems.length).toBeGreaterThan(0);
});
it('should handle user scroll interactions', () => {
const onScroll = jest.fn();
const { container } = render(
,
);
const scrollContainer = container.querySelector('.log-content__list');
expect(scrollContainer).toBeInTheDocument();
// Simulate user scroll
if (scrollContainer) {
act(() => {
scrollContainer.scrollTop = 100;
scrollContainer.dispatchEvent(new Event('scroll'));
});
}
// Component should handle scroll events
expect(scrollContainer).toBeInTheDocument();
});
});
describe('Theme switching', () => {
it('should toggle between light and dark themes', async () => {
const user = userEvent.setup();
const ThemeToggleTestWrapper: React.FC = () => {
const [logTheme, setLogThemeState] = React.useState<'light' | 'dark'>('dark');
mockUseLogViewerTheme.mockReturnValue([logTheme, setLogThemeState]);
return ;
};
const { container } = render();
const themeCheckbox = screen.getByLabelText('Dark theme');
const logViewer = container.querySelector('.pf-v6-c-log-viewer');
// Initially dark theme
expect(themeCheckbox).toBeChecked();
expect(logViewer).toHaveClass('pf-m-dark');
expect(logViewer).not.toHaveClass('log-viewer--light');
// Switch to light theme
await user.click(themeCheckbox);
await waitFor(() => {
expect(logViewer).not.toHaveClass('pf-m-dark');
expect(logViewer).toHaveClass('log-viewer--light');
});
// Switch back to dark theme
await user.click(themeCheckbox);
await waitFor(() => {
expect(logViewer).toHaveClass('pf-m-dark');
expect(logViewer).not.toHaveClass('log-viewer--light');
});
});
it('should apply light log theme modifier when main theme is dark and user selects light', () => {
mockUseTheme.mockReturnValue({
preference: 'dark',
effectiveTheme: 'dark',
systemPreference: 'dark',
setThemePreference: jest.fn(),
});
mockUseLogViewerTheme.mockReturnValue(['light', jest.fn()]);
const { container } = render();
const logViewer = container.querySelector('.pf-v6-c-log-viewer');
expect(logViewer).toHaveClass('log-viewer--light');
expect(logViewer).not.toHaveClass('pf-m-dark');
});
it('should keep theme toggle enabled when global theme is dark so user can choose light log theme', () => {
mockUseTheme.mockReturnValue({
preference: 'dark',
effectiveTheme: 'dark',
systemPreference: 'light',
setThemePreference: jest.fn(),
});
render();
const themeCheckbox = screen.getByLabelText('Dark theme');
expect(themeCheckbox).not.toBeDisabled();
});
});
describe('Wrap lines toggle', () => {
it('should be checked by default and toggle pf-m-nowrap on the log viewer', async () => {
const user = userEvent.setup();
const { container } = render();
const wrapCheckbox = screen.getByLabelText('Wrap lines');
const logViewer = container.querySelector('.pf-v6-c-log-viewer');
expect(wrapCheckbox).toBeChecked();
expect(logViewer).not.toHaveClass('pf-m-nowrap');
await user.click(wrapCheckbox);
await waitFor(() => {
expect(wrapCheckbox).not.toBeChecked();
expect(logViewer).toHaveClass('pf-m-nowrap');
});
await user.click(wrapCheckbox);
await waitFor(() => {
expect(wrapCheckbox).toBeChecked();
expect(logViewer).not.toHaveClass('pf-m-nowrap');
});
});
it('should toggle log-content__list--nowrap on the log list', async () => {
const user = userEvent.setup();
const { container } = render();
const logList = container.querySelector('.log-content__list');
expect(logList).not.toHaveClass('log-content__list--nowrap');
await user.click(screen.getByLabelText('Wrap lines'));
await waitFor(() => {
expect(logList).toHaveClass('log-content__list--nowrap');
});
});
});
describe('Download functionality', () => {
it('should show download dropdown with Download option', async () => {
const user = userEvent.setup();
render();
const toggleButton = screen.getByRole('button', { name: /download logs/i });
await user.click(toggleButton);
expect(screen.getByText('Download')).toBeVisible();
});
it('should download logs with correct filename from dropdown', async () => {
const user = userEvent.setup();
render();
// Open dropdown
await user.click(screen.getByRole('button', { name: /download logs/i }));
// Click Download option
await user.click(screen.getByText('Download'));
expect(mockSaveAs).toHaveBeenCalledWith(expect.any(Blob), 'test-task.log');
const [blob] = mockSaveAs.mock.calls[0];
expect(blob.type).toBe('text/plain;charset=utf-8');
});
it('should not download when data is empty', async () => {
const user = userEvent.setup();
render();
await user.click(screen.getByRole('button', { name: /download logs/i }));
await user.click(screen.getByText('Download'));
expect(mockSaveAs).not.toHaveBeenCalled();
});
it('should show download all option when onDownloadAll is provided', async () => {
const user = userEvent.setup();
const onDownloadAll = jest.fn().mockResolvedValue(undefined);
render(
,
);
await user.click(screen.getByRole('button', { name: /download logs/i }));
expect(screen.getByText('Download')).toBeVisible();
expect(screen.getByText('Download all task logs')).toBeVisible();
});
it('should hide download all option when onDownloadAll is not provided', async () => {
const user = userEvent.setup();
render();
await user.click(screen.getByRole('button', { name: /download logs/i }));
expect(screen.getByText('Download')).toBeVisible();
expect(screen.queryByText('Download all task logs')).not.toBeInTheDocument();
});
it('should close dropdown after selecting download option', async () => {
const user = userEvent.setup();
render();
const toggleButton = screen.getByRole('button', { name: /download logs/i });
await user.click(toggleButton);
expect(screen.getByText('Download')).toBeVisible();
await user.click(screen.getByText('Download'));
await waitFor(() => {
expect(toggleButton).toHaveAttribute('aria-expanded', 'false');
});
});
it('should handle download all functionality', async () => {
const user = userEvent.setup();
const onDownloadAll = jest.fn().mockResolvedValue(undefined);
render(
,
);
// Open dropdown and click download all
await user.click(screen.getByRole('button', { name: /download logs/i }));
await user.click(screen.getByText('Download all task logs'));
expect(onDownloadAll).toHaveBeenCalled();
// Wait for the async download to complete (promise resolves, state resets)
// then reopen dropdown and verify item is re-enabled
await user.click(screen.getByRole('button', { name: /download logs/i }));
await waitFor(() => {
const downloadAllItem = screen.getByText('Download all task logs');
expect(downloadAllItem.closest('button')).not.toBeDisabled();
});
});
it('should handle download all errors gracefully', async () => {
const user = userEvent.setup();
const consoleSpy = jest.spyOn(console, 'warn').mockImplementation();
const onDownloadAll = jest.fn().mockRejectedValue(new Error('Download failed'));
render(
,
);
// Open dropdown and click download all
await user.click(screen.getByRole('button', { name: /download logs/i }));
await user.click(screen.getByText('Download all task logs'));
// Wait for the async error handler to complete, then reopen dropdown
// and verify item is re-enabled
await user.click(screen.getByRole('button', { name: /download logs/i }));
await waitFor(() => {
const downloadAllItem = screen.getByText('Download all task logs');
expect(downloadAllItem.closest('button')).not.toBeDisabled();
});
expect(consoleSpy).toHaveBeenCalledWith('[WARN] Download failed', '');
consoleSpy.mockRestore();
});
it('should use default downloadAllLabel when not provided', async () => {
const user = userEvent.setup();
const onDownloadAll = jest.fn().mockResolvedValue(undefined);
render();
await user.click(screen.getByRole('button', { name: /download logs/i }));
expect(screen.getByText('Download all task logs')).toBeVisible();
});
});
describe('Fullscreen functionality', () => {
it('should toggle fullscreen mode', async () => {
const user = userEvent.setup();
const mockFullscreenToggle = jest.fn();
mockUseFullscreen.mockReturnValue([
false,
{ current: document.createElement('div') },
mockFullscreenToggle,
true,
]);
render();
const expandButton = screen.getByRole('button', { name: /expand/i });
await user.click(expandButton);
expect(mockFullscreenToggle).toHaveBeenCalled();
});
it('should show collapse button in fullscreen mode', () => {
mockUseFullscreen.mockReturnValue([
true,
{ current: document.createElement('div') },
jest.fn(),
true,
]);
render();
expect(screen.getByRole('button', { name: 'Collapse' })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Expand' })).not.toBeInTheDocument();
});
it('should apply fullscreen height styles', () => {
mockUseFullscreen.mockReturnValue([
true,
{ current: document.createElement('div') },
jest.fn(),
true,
]);
const { container } = render();
const logViewerContainer = container.querySelector('.log-viewer__container');
expect(logViewerContainer).toHaveStyle({ height: '100vh' });
});
});
describe('Loading and error states', () => {
it('should show loading indicator', () => {
render();
expect(screen.getByRole('progressbar')).toBeInTheDocument();
});
it('should show error alert', () => {
const errorMessage = 'Failed to fetch logs from KubeArchive';
const { container } = render();
const alert = container.querySelector('.pf-v6-c-alert.pf-m-danger');
expect(alert).toBeInTheDocument();
expect(screen.getByText(errorMessage)).toBeInTheDocument();
});
it('should show both loading and error states', () => {
const { container } = render(
,
);
expect(screen.getByRole('progressbar')).toBeInTheDocument();
const alert = container.querySelector('.pf-v6-c-alert.pf-m-danger');
expect(alert).toBeInTheDocument();
});
});
describe('Resume stream button integration', () => {
// Note: Detailed resume button behavior (scroll detection, debouncing, click handling)
// is fully tested in useAutoScrollWithResume.spec.ts
// These integration tests verify the component correctly integrates with the hook
it('should not show resume button initially', () => {
const { queryByTestId } = render();
const resumeButton = queryByTestId('resume-log-stream');
expect(resumeButton).not.toBeInTheDocument();
});
it('should integrate useAutoScrollWithResume hook when allowAutoScroll is true', () => {
const { container } = render();
// Component should render successfully with auto-scroll enabled
const logViewer = container.querySelector('.pf-v6-c-log-viewer');
expect(logViewer).toBeInTheDocument();
// The resume button wrapper should be conditionally rendered based on hook state
// (button appears/disappears based on scroll direction, tested in hook tests)
});
it('should pass allowAutoScroll prop to useAutoScrollWithResume hook', () => {
const { rerender, container } = render(
,
);
let logViewer = container.querySelector('.pf-v6-c-log-viewer');
expect(logViewer).toBeInTheDocument();
// Should handle prop change without crashing
rerender();
logViewer = container.querySelector('.pf-v6-c-log-viewer');
expect(logViewer).toBeInTheDocument();
});
it('should pass onScroll callback to useAutoScrollWithResume hook', () => {
const onScroll = jest.fn();
// Component should render without errors when onScroll is provided
expect(() => {
render();
}).not.toThrow();
});
it('should render resume button with data-test when visible', () => {
// The resume button has data-test="resume-log-stream" for testing
// It appears conditionally based on useAutoScrollWithResume hook state
const { container } = render();
// Verify component structure is correct (button will appear based on scroll state)
const logViewer = container.querySelector('.pf-v6-c-log-viewer');
expect(logViewer).toBeInTheDocument();
});
it('should pass the URL hash line target to useAutoScrollWithResume so it can pause auto-scroll', () => {
const originalPathname = window.location.pathname;
const originalSearch = window.location.search;
Object.defineProperty(window, 'location', {
configurable: true,
value: {
...window.location,
pathname: '/app/logs',
search: '?task=test',
hash: '#L3',
},
});
try {
render();
expect(mockUseAutoScrollWithResume).toHaveBeenCalledWith(
expect.objectContaining({ activeLineTarget: { start: 3, end: 3 } }),
);
} finally {
Object.defineProperty(window, 'location', {
configurable: true,
value: {
...window.location,
pathname: originalPathname,
search: originalSearch,
hash: '',
},
});
}
});
it('should pass a null line target to useAutoScrollWithResume when there is no line hash', () => {
render();
expect(mockUseAutoScrollWithResume).toHaveBeenCalledWith(
expect.objectContaining({ activeLineTarget: null }),
);
});
});
describe('Data updates', () => {
it('should update log content when data changes', () => {
const { container, rerender } = render();
let logList = container.querySelector('.log-content__list');
expect(logList).toBeInTheDocument();
const newData = 'new line 1\nnew line 2\nnew line 3';
rerender();
logList = container.querySelector('.log-content__list');
expect(logList).toBeInTheDocument();
});
it('should handle empty data', () => {
const { container } = render(
,
);
const logList = container.querySelector('.log-content__list');
expect(logList).toBeInTheDocument();
});
it('should handle very long log data', () => {
const longData = Array.from({ length: 1000 }, (_, i) => `line ${i + 1}`).join('\n');
const { container } = render(
,
);
const logList = container.querySelector('.log-content__list');
expect(logList).toBeInTheDocument();
// Should use virtualization (only render visible items)
const visibleItems = container.querySelectorAll('.pf-v6-c-log-viewer__list-item');
expect(visibleItems.length).toBeLessThan(1000);
});
});
describe('Sections support', () => {
const sectionProps = {
...defaultProps,
sections: [
{ containerName: 'step-build', data: 'building...\ndone' },
{ containerName: 'step-test', data: 'testing...\npassed' },
],
};
it('should render log content from sections', () => {
const { container } = render();
const logList = container.querySelector('.log-content__list');
expect(logList).toBeInTheDocument();
expect(logList?.textContent).toContain('building...');
expect(logList?.textContent).toContain('testing...');
});
it('should strip ANSI codes from section data', () => {
const sectionsWithAnsi = {
...defaultProps,
sections: [
{
containerName: 'step-build',
data: '\x1b[32mSuccess\x1b[0m\nplain line',
},
],
};
const { container } = render();
const logList = container.querySelector('.log-content__list');
expect(logList?.textContent).not.toContain('\x1b');
expect(logList?.textContent).toContain('Success');
});
it('should support download when using sections', async () => {
const user = userEvent.setup();
render();
await user.click(screen.getByRole('button', { name: /download logs/i }));
await user.click(screen.getByText('Download'));
expect(mockSaveAs).toHaveBeenCalledWith(expect.any(Blob), 'test-task.log');
});
});
describe('Expand/Collapse all sections', () => {
const foldedSections = [
{ containerName: 'BUILD', data: 'compile\nlink', isCompleted: true },
{ containerName: 'TEST', data: 'runningtests', isCompleted: true },
];
const expandedSections = [
{ containerName: 'BUILD', data: 'compile\nlink', isCompleted: false },
{ containerName: 'TEST', data: 'runningtests', isCompleted: false },
];
it('should not render the expand all button by default', () => {
render();
expect(screen.queryByRole('button', { name: 'Expand/Collapse all' })).not.toBeInTheDocument();
});
it('should render the expand/collapse button with dynamic label when allowExpandAllSections is true', () => {
render();
// Accessible name stays stable via aria-label
const toggleButton = screen.getByRole('button', { name: 'Expand/Collapse all' });
expect(toggleButton).toBeInTheDocument();
// Default single section is in-progress (expanded), so the visible label is "Collapse all"
expect(screen.getByText('Collapse all')).toBeInTheDocument();
expect(toggleButton).toHaveAttribute('aria-label', 'Expand/Collapse all');
});
it('should show "Expand all" initially when sections start folded', () => {
render();
expect(screen.getByText('Expand all')).toBeInTheDocument();
expect(screen.queryByText('Collapse all')).not.toBeInTheDocument();
});
it('should show "Collapse all" initially when sections start expanded', () => {
render();
expect(screen.getByText('Collapse all')).toBeInTheDocument();
expect(screen.queryByText('Expand all')).not.toBeInTheDocument();
});
it('should toggle the label from "Expand all" to "Collapse all" and back', async () => {
const user = userEvent.setup();
render();
const toggleButton = screen.getByRole('button', { name: 'Expand/Collapse all' });
expect(screen.getByText('Expand all')).toBeInTheDocument();
await user.click(toggleButton);
expect(screen.getByText('Collapse all')).toBeInTheDocument();
await user.click(toggleButton);
expect(screen.getByText('Expand all')).toBeInTheDocument();
});
it('should toggle the label from "Collapse all" to "Expand all" and back', async () => {
const user = userEvent.setup();
render();
const toggleButton = screen.getByRole('button', { name: 'Expand/Collapse all' });
expect(screen.getByText('Collapse all')).toBeInTheDocument();
await user.click(toggleButton);
expect(screen.getByText('Expand all')).toBeInTheDocument();
await user.click(toggleButton);
expect(screen.getByText('Collapse all')).toBeInTheDocument();
});
it('should render a direction icon inside the expand/collapse button', () => {
const { rerender } = render(
,
);
let toggleButton = screen.getByRole('button', { name: 'Expand/Collapse all' });
// AngleDownIcon when collapsed ("Expand all")
expect(toggleButton.querySelector('.pf-v6-c-button__icon')).toBeInTheDocument();
rerender();
toggleButton = screen.getByRole('button', { name: 'Expand/Collapse all' });
// AngleUpIcon when expanded ("Collapse all")
expect(toggleButton.querySelector('.pf-v6-c-button__icon')).toBeInTheDocument();
});
it('should expand all folded sections when the button is clicked', async () => {
const user = userEvent.setup();
render();
expect(screen.queryByText('compile')).not.toBeInTheDocument();
expect(screen.queryByText('runningtests')).not.toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Expand/Collapse all' }));
expect(screen.getByText('compile')).toBeInTheDocument();
expect(screen.getByText('runningtests')).toBeInTheDocument();
});
it('should collapse all expanded sections when the button is clicked', async () => {
const user = userEvent.setup();
render();
expect(screen.getByText('compile')).toBeInTheDocument();
expect(screen.getByText('runningtests')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Expand/Collapse all' }));
expect(screen.queryByText('compile')).not.toBeInTheDocument();
expect(screen.queryByText('runningtests')).not.toBeInTheDocument();
});
it('should toggle back to collapsed on a second click', async () => {
const user = userEvent.setup();
render();
const toggleButton = screen.getByRole('button', { name: 'Expand/Collapse all' });
await user.click(toggleButton);
expect(screen.getByText('compile')).toBeInTheDocument();
await user.click(toggleButton);
expect(screen.queryByText('compile')).not.toBeInTheDocument();
expect(screen.queryByText('runningtests')).not.toBeInTheDocument();
});
});
describe('Task information display', () => {
it('should display task name with truncation', () => {
const longTaskName = 'very-long-task-name-that-should-be-truncated-in-the-ui';
const taskRunWithLongName = {
...mockTaskRun,
spec: { taskRef: { name: longTaskName } },
};
const { container } = render();
const truncateElement = container.querySelector('.pf-v6-c-truncate');
expect(truncateElement).toBeInTheDocument();
expect(truncateElement).toHaveTextContent(longTaskName);
});
it('should use metadata name when taskRef is not available', () => {
const taskRunWithoutTaskRef = {
...mockTaskRun,
spec: {},
};
render();
expect(screen.getByText('test-task-run')).toBeInTheDocument();
});
it('should not show task name section when no task information is available', () => {
const { container } = render();
const truncateElement = container.querySelector('.pf-v6-c-truncate');
expect(truncateElement).not.toBeInTheDocument();
});
it('should not show task name when task name is empty string', () => {
const taskRunEmptyName = {
...mockTaskRun,
spec: { taskRef: { name: '' } },
metadata: { name: '' },
};
const { container } = render();
const truncateElement = container.querySelector('.pf-v6-c-truncate');
expect(truncateElement).not.toBeInTheDocument();
});
it('should not show task name when task metadata is missing', () => {
const taskRunNoNames = { ...mockTaskRun, spec: {}, metadata: {} };
const { container } = render();
const truncateElement = container.querySelector('.pf-v6-c-truncate');
expect(truncateElement).not.toBeInTheDocument();
});
});
describe('Scroll callback integration', () => {
it('should call onScroll callback with scroll information', () => {
const onScroll = jest.fn();
render();
expect(onScroll).toHaveBeenCalledWith({
scrollDirection: 'forward',
scrollOffset: 0,
scrollUpdateWasRequested: true,
});
});
});
describe('Search integration', () => {
it('should render search input by default', () => {
render();
const searchInput = screen.queryByPlaceholderText('Search');
expect(searchInput).toBeInTheDocument();
});
it('should render search input when showSearch is true', () => {
render();
const searchInput = screen.getByPlaceholderText('Search');
expect(searchInput).toBeInTheDocument();
});
});
describe('Keyboard shortcuts popover', () => {
it('should render the keyboard shortcut button', () => {
render();
const button = screen.getByRole('button', { name: /show keyboard shortcuts/i });
expect(button).toBeInTheDocument();
});
it('should toggle the shortcuts popover on button click', async () => {
const user = userEvent.setup();
render();
const button = screen.getByRole('button', { name: /show keyboard shortcuts/i });
await user.click(button);
expect(screen.getByText('Keyboard shortcuts')).toBeInTheDocument();
expect(screen.getByText('Scroll up one line')).toBeInTheDocument();
expect(screen.getByText('Scroll down one line')).toBeInTheDocument();
expect(screen.getByText('Scroll to top')).toBeInTheDocument();
expect(screen.getByText('Scroll to bottom')).toBeInTheDocument();
expect(screen.getByText('Click the log area to enable these shortcuts.')).toBeInTheDocument();
});
});
describe('Edge cases', () => {
it('should handle null taskRun gracefully', () => {
expect(() => {
render();
}).not.toThrow();
});
it('should handle missing taskRun status', () => {
const taskRunWithoutStatus = {
...mockTaskRun,
status: undefined,
};
expect(() => {
render();
}).not.toThrow();
});
it('should handle data with only newlines', () => {
const { container } = render(
,
);
const logList = container.querySelector('.log-content__list');
expect(logList).toBeInTheDocument();
});
it('should handle data with special characters', () => {
const specialData = 'line with tags\nline with & ampersand\nline with "quotes"';
const { container } = render(
,
);
const logList = container.querySelector('.log-content__list');
expect(logList).toBeInTheDocument();
});
});
});